Rails 中 has_many.size 大于 0?

ser*_*erg 3 activerecord model ruby-on-rails has-many where-clause

所以这有效并获取我需要的数据:

  def has_function
    services = []
    Service.find_each do |s|
      if s.functions.size > 0
        services << s
      end
    end
    return services
  end
Run Code Online (Sandbox Code Playgroud)

但是,该方法返回一个数组,我打算将其链接到其他地方:

Service.has_function.visible.includes(:layer)
undefined method `where' for #<Array:0x007faad487a970>
Run Code Online (Sandbox Code Playgroud)

我如何检查这一点并返回可链接的东西?

Jam*_*els 5

您需要在连接中执行爵士乐,以便所有内容都保留在 ActiveRecord 中。另外...这会快得多,因为它是单个 SQL 查询。只要确保您有正确的索引即可。

Service.joins(:functions).visible.includes(:layer)
Run Code Online (Sandbox Code Playgroud)

如果你想检查是否存在任何超出存在的东西,请说计数 > 1;你必须进行分组/拥有。

Service.
  joins(:functions).
  select('services.*, count(functions.id) as function_count').
  group('services.id').
  having('function_count > 2')
Run Code Online (Sandbox Code Playgroud)