How to filter by the number of associations?

Let's say I have models that look like this:

class Foo < ActiveRecord::Base
    has_many :bars, :through => :cakes
    has_many :cakes
end

class Bar < ActiveRecord::Base
    has_many :foos, :through => :cakes
    has_many :cakes
end

class Cake < ActiveRecord::Base
    belongs_to :foo
    belongs_to :bar
end

How do I get all foos that have 10 or more bars (and therefore 10 or more cakes)?

+3
source share
2 answers
Foo.all(:joins => :cakes, 
  :group => "cakes.foo_id", 
  :having => "count(cakes.bar_id) >= 10")
+5
source

Ok, I tried to answer above, but had a problem.

for our purposes Father has_many: sons, okay?

I wanted to find fathers who had zero sons.

the above did not work because it created an inner connection ... thus filtering out all fathers without sons.

the following worked for me:

Father.includes(:sons).group('fathers.id').having( 'count(sons.id)=0' )

and this also works for any other filter you need

Father.includes(:sons).group('fathers.id').having( 'count(sons.id)=3' )

+1
source

Source: https://habr.com/ru/post/1720037/


All Articles