rails3 scope for count of children in has_many relationship

后端 未结 4 1717
感动是毒
感动是毒 2021-02-14 03:08

trying to do a scope in rails3.

:book has_many :chapters 

I want scope :long to return books with > 10 chapters.

How best to structure

4条回答
  •  爱一瞬间的悲伤
    2021-02-14 03:53

    Ah - to answer my own question in the comment above, I had to put the count in the HAVING:

    class Book
      scope :long, joins(:chapters).
        select('books.id').
        group('books.id').
        having('count(chapters.id) > 10')
    end
    

提交回复
热议问题