has_many:through - 对连接表应用限制

时间:2013-09-29 16:05:22

标签: ruby-on-rails ruby-on-rails-3 activerecord associations has-many-through

我知道我可以对has_many :through中的关联应用限制,即:

class Post
  has_many :commenters, through: :comments, uniq: true, limit: 10
end

最多返回10 commenters。但是如果我只想知道前10条评论的人呢? (例如,如果有一个乒乓评论帖子,它只会产生2个结果)。换句话说,如何限制此查询中comments的数量?

1 个答案:

答案 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

免责声明:代码未经过测试。