当我进行upvote / downvote

时间:2015-12-09 15:38:03

标签: ruby-on-rails ruby ruby-on-rails-4 voting acts-as-votable

我试图允许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)

1 个答案:

答案 0 :(得分: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