Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails活动记录查询表的关联数_Ruby On Rails_Rails Activerecord - Fatal编程技术网

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')