Reputation: 10035
I have a foo
table that has many bar
s. How do I find all foo
s that have more than 5 bar
s? I was thinking something like Foo.where(bar.length > 5)
but that didn't work.
Upvotes: 0
Views: 34
Reputation: 15985
Check
Foo.joins(:bars).group('foos.id').having('COUNT(bars.foo_id) > 5')
Upvotes: 1
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