rails3 scope for count of children in has_many relationship

后端 未结 4 1712
感动是毒
感动是毒 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?

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-14 03:53

    An alternative is to make a subquery. While the join is more correct (and possibly also leads to better performance), you may end up with strange results if you combine multiple scopes that try to do grouping. A subquery is much less intrusive. For this example, it would be something like:

    class Book
      scope :with_chapters_count, -> {
        select('books.*').
        select('(select count(chapters.id) from chapters where chapters.book_id = books.id) as chapters_count')
      }
      scope :long, -> {
        with_chapters_count.where("chapters_count > 10")
      }
    end
    
    0 讨论(0)
  • 2021-02-14 04:02

    In rails 4.0 this version works. You have to count() in the having clause. It seems that having clause doesn't see 'as n_chapters'.

    0 讨论(0)
提交回复
热议问题