act_as_votable не работает, когда я поднимаю / понижаю
Я пытаюсь разрешить treatment
быть голосуемым с положительными или отрицательными голосами, но методы, предоставляемые act_as_votable, не работают должным образом. Когда я пытаюсь отобразить сумму положительных и отрицательных голосов, она каждый раз возвращает 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 ответ
Благодаря помощи Кристяна я понял, что вставка не происходит. Я определил current_user в методах upvote и downvote. Пересмотренные рабочие версии выглядят так.
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