【问题标题】:has_many :through - Apply a limit to the join tablehas_many :through - 对连接表应用限制
【发布时间】:2013-09-29 16:05:21
【问题描述】:

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

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

这将返回最多 10 个commenters。但是,如果我只想知道贡献了前 10 个 cmets 的人怎么办? (例如,如果有一个乒乓评论线程,它只会产生 2 个结果)。换句话说,我如何限制这个查询中comments的数量?

【问题讨论】:

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


    【解决方案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
    

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

    【讨论】:

    • 您应该为此使用连接。
    • 是的,使用 has_many 语法可能无法实现。 @depa 你是什么意思?我注意到这可能是一个更快的查询,使用诸如 Comment.find(cmets.uniq(true).pluck(:commenter_id)) 之类的东西......不确定这是否是 depa 的意思。
    • 我同意我发布的查询还有很大的改进空间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多