0

我试图允许treatment通过 upvotes 或 downvotes 进行投票,但 act_as_votable 提供的方法似乎没有按预期工作。当我尝试显示 upvotes-downvotes 的总和时,它每次都返回 0,这意味着投票没有像应有的那样注册。

我的treatments_controller.rb

def upvote
  @treatment = Treatment.find(params[:id])
  @treatment.upvote_by @current_user

  render 'show'
end

def downvote
  @treatment = Treatment.find(params[:id])
  @treatment.downvote_by @current_user

  redirect_to treatments_path
end

我的treatment.rb

class Treatment < ActiveRecord::Base
acts_as_votable


 has_many :review
 has_one :service


    def score
  self.get_upvotes.size - self.get_downvotes.size
end

end

我的routes.rb

resources :treatments do
  member do
    put "like", to: "treatments#upvote"
    put "dislike", to: "treatments#downvote"
  end
end

和我的treatments/show.html.erb

<div class="container">
    <div class="row">
      <div class="col-sx-12 col-sm-12 col-md-8">
        <h3><%= @treatment.name %></h3></br></br>
 <h3>
           <%= link_to "upvote", like_treatment_path(@treatment), method: :put %></br>
            <%= link_to "downvote", dislike_treatment_path(@treatment), method: :put %></br>
            <%= @treatment.score %></br> </h3>

服务器日志显示以下内容

Started PUT "/treatments/1/like" for ::1 at 2015-12-09 16:22:14 +0000
Processing by TreatmentsController#upvote as HTML
  Parameters: {"authenticity_token"=>"hQnqV+OZ6m/9kFnr5YH6j563DIjyKfA4K/8fH6kpFbXbJRbsHCcNYn1AX4usZmUNXPlnFpxHMwTM8ilFxcbdhQ==", "id"=>"1"}
Geokit is using the domain: localhost
  Treatment Load (0.5ms)  SELECT  "treatments".* FROM "treatments" WHERE "treatments"."id" = ? LIMIT 1  [["id", 1]]
   (0.5ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = ? AND "votes"."vote_scope" IS NULL  [["votable_id", 1], ["votable_type", "Treatment"], ["vote_flag", "t"]]
   (0.0ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = ? AND "votes"."vote_scope" IS NULL  [["votable_id", 1], ["votable_type", "Treatment"], ["vote_flag", "f"]]
  Rendered treatments/show.html.erb within layouts/application (6.5ms)
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]
Completed 200 OK in 569ms (Views: 563.3ms | ActiveRecord: 1.0ms)
4

1 回答 1

0

感谢 Kristjan 的帮助,我意识到没有发生插入。我在 upvote 和 downvote 方法中定义了 current_user。修改后的工作版本看起来像这样。

 def upvote
  current_user = User.find_by_id(session[:user_id])
  @treatment = Treatment.find(params[:id])
  @treatment.upvote_by current_user

  render 'show'
end

def downvote
  current_user = User.find_by_id(session[:user_id])
  @treatment = Treatment.find(params[:id])
  @treatment.downvote_by current_user

  render 'show'
end
于 2015-12-09T16:47:27.440 回答