【问题标题】:Find all objects that have greater than x of a certain association查找具有某个关联的大于 x 的所有对象
【发布时间】:2015-04-16 04:43:39
【问题描述】:

我有很多Farms,每个农场都有很多animals。我需要找到每一个拥有超过 5 只动物的农场。

我需要一些类似的东西...:

Farm.where(animals.count > 5)  

更新/回答:

Farm.joins(:animals).group("farm_id").having("count(farm_id) > 5")

【问题讨论】:

  • 如果我是你,我会使用 Parkash 的答案。不过你也可以试试squeel gem。它可能会有所帮助

标签: ruby-on-rails ruby activerecord


【解决方案1】:

试试:

Farm.joins(:animals).group("farm.id").having("count(animals.id) > ?",5)

参考:https://stackoverflow.com/a/9370734/429758

【讨论】:

  • 我相信这很接近,但它无法识别animals.id
【解决方案2】:

考虑在 Farm -> Animal 上实现 counter_cache

class Farm < ActiveRecord::Base
  has_many :animals
end

class Animal < ActiveRecord::Base
  belongs_to :farm, counter_cache: true
end

不要忘记将animals_count(整数)添加到farms 表中。

class AddAnimalCounterCacheToFarm < ActiveRecord::Migration
  def up
    add_column :farms, :animals_count, :integer
    # if you need to populate for existing data
    Farm.reset_column_information
    Farm.find_each |farm|
      farm.update_attribute :animals_count, farm.animals.length
    end
  end

  def down
    remove_column :farms, :animals_count
  end
end

寻找有 5 只或更多动物的农场

Farm.where("farms.animals_count >= 5")

【讨论】:

  • 这些行对我不起作用:Farm.reset_column_information Farm.find_each |farm| farm.update_attribute :animals_count, farm.animals.length end 我用这个替换它们来修复它:Farm.find_each { |u| Farm.reset_counters(u.id, :animals) }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 2016-08-30
相关资源
最近更新 更多