Ruby on rails Rails活动记录查询表的关联数
我有一个Ruby on rails Rails活动记录查询表的关联数,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我有一个foo表,其中有许多条。如何查找所有具有超过5个条的foos?我在想类似于Foo.where(bar.length>5)的东西,但这不起作用。您可以使用“首先添加此代码并添加新列” class Bar < ActiveRecord::Base belongs_to :Foo, counter_cache: true # ... end # add a migration add_column :Foo, :bars_count, :integer, default: 0
foo
表,其中有许多条。如何查找所有具有超过5个条的foo
s?我在想类似于Foo.where(bar.length>5)
的东西,但这不起作用。您可以使用“首先添加此代码并添加新列”
class Bar < ActiveRecord::Base
belongs_to :Foo, counter_cache: true
# ...
end
# add a migration
add_column :Foo, :bars_count, :integer, default: 0
类栏
然后你就可以执行了
Foo.where(:bar\u count>5)
这可能与检查有关
Foo.joins(:bars).group('foos.id').having('COUNT(bars.foo_id) > 5')