【问题标题】:Finding user total votes recieved on posts by other users查找用户在其他用户的帖子上收到的总票数
【发布时间】:2014-02-14 13:54:47
【问题描述】:

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

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

我正在使用 rails 4 btw,它与两个 gem 兼容。

在我的用户模型中:

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

一切似乎都运行良好。但是当试图计算一个用户的总票数时(用户在所有 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" = ?

我试过了:

@user.find_voted_items.count

@user.get_voted(Comment).count ? 

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

似乎没有任何效果。我猜这与 commontator gem 处理代理关联关系的方式有关。如何呈现特定用户在所有 cmets 上收到的总票数?非常感谢任何帮助!

编辑:我确实运行了所有迁移。

【问题讨论】:

  • 你运行迁移了吗?
  • 是的!我应该提到这一点!
  • 在 commontator gem 页面中,有一个部分描述了如何与acts_as_votable 集成。你检查那部分了吗? github.com/lml/commontator#voting。看来您必须添加该设置,然后重新启动您的应用程序。
  • @KatieHeidmann 我想知道用户模型中的has_many :comments 是否导致了这一切。当您在模型中包含acts_as_commentator 时,它已经为您添加了关系。

标签: ruby-on-rails ruby ruby-on-rails-4 gem


【解决方案1】:

你不应该在 cmets 上点票吗? User 模型 acts_as_voter 因此,根据 gem 上的文档,您可以检索用户使用 find_voted_items 投票的项目列表,但 Comment 模型是您可以计算 votes 的模型,因为那是用户投票的内容。

编辑,给定 cmets。最简单的情况是,您可能需要类似这样的东西:

sum = 0
@user.comments.each do |comment|
    sum += comment.votes.count
end

尽管您可以使用inject 甚至在投票字段上使用精心构建的“where 子句”使用 Activerecord#sum 来使这一点更有说服力。

【讨论】:

  • 是的,这就是我想要做的。我正在尝试呈现特定用户所做的所有 cmets 的总分。有点像他们的业力。我应该使用什么方法?
  • 好吧,我只阅读了 gem 的文档,但我认为你会想要获取用户制作的 cmets 集合,然后遍历它们以获得每条评论的分数。
  • 这给了我:SQLite3::SQLException: 没有这样的列:commontator_cmets.commontator_id: SELECT "commontator_cmets".* FROM "commontator_cmets" WHERE "commontator_cmets"."commontator_id" = ? AND "commontator_cmets"."commontator_type" = ?
  • 好的 - 好吧,在没有看到更多代码的情况下进行调试有点棘手 - 你的 schema.rb 文件中有什么,或者如果你有 github 上的项目,请将我们指向那里......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2011-02-17
相关资源
最近更新 更多