ROR:多态投票模型中有问题的私有方法

时间:2016-08-19 18:08:04

标签: ruby-on-rails

我正在尝试使用类似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更改。

0 个答案:

没有答案