Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails3 scope for count of children in has_many relationship

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 this scope (without use of counter cache) ?

thanks!

like image 590
istan Avatar asked Nov 23 '11 23:11

istan


3 Answers

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?

like image 94
leonardoborges Avatar answered Nov 10 '22 13:11

leonardoborges


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
like image 44
Chris Doyle Avatar answered Nov 10 '22 13:11

Chris Doyle


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'.

like image 1
dr0p Avatar answered Nov 10 '22 14:11

dr0p