我正在尝试使用类似SO / reddit的投票结构创建应用。我对我的jokes
模型进行了投票,并尝试为我的recipes
模型实施该投票。
到目前为止,我已将erb
作为recipes
的投票:
<div class="text-center col-xs-1">
<% if current_user %>
<div class="width: 100%"><%= link_to " ", recipe_up_vote_path(recipe), class: 'upvote glyphicon glyphicon-chevron-up', method: :post, style: "margin-right: 0; margin-left: 0" %></div>
<div class="width: 100%"><h3 style="margin-top: 0; margin-bottom: 0"><strong><%= recipe.rankpoints %></strong></h3></div>
<div class="width: 100%"><%= link_to " ", recipe_down_vote_path(recipe), class: 'downvote glyphicon glyphicon-chevron-down', method: :post, style: "margin-right: 0; margin-left: 0" %></div>
<% else %>
<div class="width: 100%"><%= link_to " ", new_user_session_path, class: 'upvote glyphicon glyphicon-chevron-up', method: :post, style: "margin-right: 0; margin-left: 0" %></div>
<div class="width: 100%"><h3 style="margin-top: 0; margin-bottom: 0"><strong><%= recipe.rankpoints %></strong></h3></div>
<div class="width: 100%"><%= link_to " ", new_user_session_path, class: 'downvote glyphicon glyphicon-chevron-down', method: :post, style: "margin-right: 0; margin-left: 0" %></div>
<% end %>
</div>
这是我的votes_controller
:
class VotesController < ApplicationController
def up_vote
update_vote(1)
redirect_to :back
end
def down_vote
update_vote(-1)
redirect_to :back
end
private
def update_vote(new_value)
# @joke = Joke.find(params[:joke_id]) <<<<DELETED THIS LINE
user = current_user
if @joke.user.votes == nil
@vote = current_user.votes.create(value: new_value, voteable: @thing)
if @vote
@vote.update_attribute(:value, new_value)
else
@vote = current_user.votes.create(value: new_value, voteable: @thing)
end
else
flash[:notice] = "C'mon man, you know you only get one vote."
end
end
end
我遇到问题的地方是private
中的update_vote
votes_controller
方法。显然,当我尝试对recipe
投票时,它会引发错误,因为它是为jokes
模型配置的。如果我将其更改为与recipe
投票相对应,则该笑话将引发错误。如何根据votes
?
更新
我更新了私有方法,使其具有@thing
而不是@joke
或@recipe
,然后我在相应的适当方法中定义@thing = @joke
或@thing = @recipe
控制器。此更改消除了被抛出的错误,但rankpoints
的值在投票时不会从0
更改。