stackjlei
stackjlei

Reputation: 10035

Rails active record query table by number of its associations

I have a foo table that has many bars. How do I find all foos that have more than 5 bars? I was thinking something like Foo.where(bar.length > 5) but that didn't work.

Upvotes: 0

Views: 34

Answers (2)

Amit Patel
Amit Patel

Reputation: 15985

Check

Foo.joins(:bars).group('foos.id').having('COUNT(bars.foo_id) > 5')

Upvotes: 1

buncis
buncis

Reputation: 2502

you can use counter_cache first add this code and add new column

class Bar < ActiveRecord::Base
  belongs_to :Foo, counter_cache: true
  # ...
end

# add a migration
add_column :Foo, :bars_count, :integer, default: 0

then you can exec with

Foo.where(:bars_count > 5)

this question maybe relevant

Upvotes: 0

Related Questions