activerecord信誉系统:用户投票后隐藏按钮

时间:2016-04-11 19:59:42

标签: ruby-on-rails ruby activerecord

我使用Railscast教程来实现activerecord信誉系统:http://railscasts.com/episodes/364-active-record-reputation-system?view=comments

但是在用户投票后我无法隐藏按钮。

我是这样做的:

发布控制器:

def accept
  value = params[:type] == "accept" ? 1 : -1  # vote type = accept
  @improvement_action = ImprovementAction.find(params[:id])
  @improvement_action.add_or_update_evaluation(:accepts, value, current_user)
  redirect_to :back, notice: "You accepted the answer!"
end

发布模型:

has_reputation :accepts, source: :user, aggregated_by: :sum

用户模型:

has_many :evaluations, class_name: "RSEvaluation", as: :source   #accept answer (activerecord reputation-system gem)

has_reputation :accepts, source: {reputation: :accepts, of: :improvement_actions}, aggregated_by: :sum


def voted_for? improvement_action
    evaluations.where(target_type: improvement_action.class, target_id: improvement_action.id).exists?
end

在视图中如下调用:

<% if current_user && current_user.voted_for?(improvement_action) %>
  VOTED
<% else %>
  NOT VOTED
  <%= link_to "up", accept_improvement_action_path(improvement_action, type: "accept"), method: "post" %>
<% end %>

我做错了什么?像这样似乎总是投票

1 个答案:

答案 0 :(得分:1)

尝试更改

<% if current_user && !current_user.voted_for?(improvement_action) %>
        VOTED
      <%     else %>
     NOT VOTED

        <%= link_to "up", accept_improvement_action_path(improvement_action, type: "accept"), method: "post" %>
        <% end %>

<% if current_user && !current_user.voted_for?(improvement_action) %>
  NOT VOTED
  <%= link_to "up", accept_improvement_action_path(improvement_action, type: "accept"), method: "post" %>
<% end %>

首先,查看上行链接是否显示

更新

显然,railscast教程已经过时,宝石已经改变了很多。它不再起作用的原因是因为数据库模式完全改变了,它不再使用多态。以下代码应该可以解决您的问题:

class User < ActiveRecord::Base
  has_many :posts

  has_reputation :accepts, source: {reputation: :accepts, of: :posts}, aggregated_by: :sum

  def voted_for?(post)
    Post.where(id: post.id).evaluated_by(:accepts, self)
  end

end