0

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.

stackjlei
  • 9,485
  • 18
  • 65
  • 113

2 Answers2

1

Check

Foo.joins(:bars).group('foos.id').having('COUNT(bars.foo_id) > 5')
Amit Patel
  • 15,609
  • 18
  • 68
  • 106
0

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

buncis
  • 2,148
  • 1
  • 23
  • 25