【问题标题】:Rendering user vote count渲染用户投票计数
【发布时间】:2014-02-13 21:34:51
【问题描述】:

我将这个 gem 用于 cmets:https://github.com/lml/commontator

可以轻松插入此 gem 以对 cme​​ts 进行投票:https://github.com/ryanto/acts_as_votable

一切似乎都运行良好。但是当试图计算一个用户的总票数时(用户在所有 cmets 上收到的总票数)(业力)

<%= @user.votes.count %>

我收到此错误

undefined method `votes' for #<User:0x0000010dbf23a0>

所以我尝试了这个:

<%= @user.comments.map{|c| c.votes.count}.inject(:+) %>

导致另一个错误:

SQLite3::SQLException: no such column: commontator_comments.commontator_id: SELECT "commontator_comments".* FROM "commontator_comments"  WHERE "commontator_comments"."commontator_id" = ? AND "commontator_comments"."commontator_type" = ?

如何呈现特定用户在所有 cmets 上获得的总票数?

【问题讨论】:

  • 你试过@user.find_voted_items.count@user.get_voted(Comment).count吗?
  • 是的,都给我一个 NoMethodError
  • 你添加acts_as_voter到用户模型了吗?
  • 太棒了!刚刚做到了,现在当使用@user.find_voted_items.count 时,它给了我用户投票的项目数。我正在尝试计算用户收到的总票数。
  • 例如,如果用户评论了两次,其中一条评论获得 4 票,另一条评论获得 2 票,则他的投票数为 6

标签: ruby-on-rails ruby gem


【解决方案1】:

假设你有这个设置

class User < ActiveRecord::Base
  acts_as_voter
  acts_as_commentator
  has_many :comments
end

class Comment < ActiveRecord::Base
  acts_as_votable
  belongs_to :user
end

安装commentatoracts_as_votable gems后如下

rails generate acts_as_votable:migration
rake commontator:install
rake db:migrate

你应该可以得到这样的票数

@user.comments.collect{|c| c.votes.size}.inject(:+)

【讨论】:

  • 现在我得到“找不到表'cmets'”
  • 非常感谢您的回复和努力,我只是不知道为什么要进行投票计数变得不可能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
相关资源
最近更新 更多