有文章和评论。
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :article, counter_cache: true
end
您可以通过这样的操作来计算注释的数量:@article.comments_count
问题是--你如何计算在一篇特定@文章上留下评论的唯一用户的数量?(注意:唯一的用户可以留下多个注释)
下面是一个场景:
注释计数=3
评论人(留下评论的唯一用户) count =2
发布于 2015-02-05 23:04:02
Rails有一个很好的 query method,它使这个特定的查询更容易生成:
Comment.where(article_id: article.id).select(:user_id).distinct.count
它生成以下SQL:
SELECT DISTINCT COUNT(DISTINCT "comments"."user_id") FROM "comments" WHERE "comments"."article_id" = ?
这种方法的好处是允许数据库完成繁重的工作。数据库通常比在Ruby中直接操作对象快几个数量级。
如果您愿意按以下方式修改您的Article
类:
class Article < ActiveRecord::Base
has_many :comments
has_many :commenters, through: :comments, source: :user
has_many :unique_commenters, -> { distinct }, through: :comments, source: :user
end
还可以使用以下代码生成查询:
article.unique_commenters
它生成以下SQL:
SELECT DISTINCT "users".* FROM "users" INNER JOIN "comments" ON "users"."id" = "comments"."user_id" WHERE "comments"."article_id" = ?
发布于 2015-02-05 19:20:40
尝试使用pluck
和uniq
@article.comments.uniq.pluck(:user_id)
或者仅仅是pluck
@article.comments.pluck("DISTINCT user_id")
发布于 2015-02-05 19:20:42
article.comments.collect(&:user).uniq{|user| user.id}.count
https://stackoverflow.com/questions/28352136
复制相似问题