我知道我可以对has_many :through
中的关联应用限制,即:
class Post
has_many :commenters, through: :comments, uniq: true, limit: 10
end
最多返回10 commenters
。但是如果我只想知道前10条评论的人呢? (例如,如果有一个乒乓评论帖子,它只会产生2个结果)。换句话说,如何限制此查询中comments
的数量?
答案 0 :(得分:1)
将关系定义与您想要进行的查询分开可能会更好。
class Post
has_many :commenters, through: :comments
def last_commenters
comments.order('created_at DESC').limit(10).map{|c|c.commenter}.uniq
end
end
免责声明:代码未经过测试。