Rails有精彩distinct
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" = ?