Find all objects that have greater than x of a certain association

假如想象 提交于 2019-12-22 05:26:28

问题


I have many Farms and each farm has many animals. I need to find every farm that has more than 5 animals.

I need something along the lines of this...:

Farm.where(animals.count > 5)  

Update/Answer:

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

回答1:


Try:

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

Ref: https://stackoverflow.com/a/9370734/429758




回答2:


Consider implementing counter_cache on Farm -> Animal

class Farm < ActiveRecord::Base
  has_many :animals
end

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

Don't forget to add animals_count (integer) to the farms table.

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

To find Farms with 5 or more Animals

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


来源:https://stackoverflow.com/questions/29665494/find-all-objects-that-have-greater-than-x-of-a-certain-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!