rails3 scope for count of children in has_many relationship

后端 未结 4 1703
感动是毒
感动是毒 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:52

    This should get you going:

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

    Does it help?

提交回复
热议问题