【问题标题】:activerecord reputation system: hide buttons after user voteactiverecord 信誉系统:用户投票后隐藏按钮
【发布时间】:2016-08-02 04:08:47
【问题描述】:

我正在使用 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 %>

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

【问题讨论】:

  • 如果用户没有投票则显示链接和Voted?你的 if 条件倒置了吗?
  • 是的,没错,我换了我的错误。但是问题是一样的,因为不管我投不投,看起来都是一样的
  • 我怀疑add_or_update_evaluation(:accepts, value, current_user) 不起作用。
  • 我认为您在此处的视图文件中缺少 if 条件,您可以重新发布吗?
  • 是的,它没有出现,我编辑了

标签: ruby-on-rails ruby activerecord


【解决方案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 %>

先看看up链接有没有出现

更新

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

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

【讨论】:

  • 那么点击链接会发生什么?
  • 刷新页面后显示相同(只投票一次,但投票后不能隐藏按钮)
  • 所以投票已经完成,并且在数据库中成功更新了对吧?只是up 按钮还在显示对吗?
  • 你能去 Rails 控制台,找到一个投票给improvement_actionuser。并致电user.voted_for?(improvement_action),看看它是否给你真实
  • 它给了我错误:>> current_user.voted_for?(improvement_action) =&gt; false
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多