Find all objects that have more than x of some association

I have a lot Farmsand every farm has a lot animals. I need to find every farm with more than 5 animals.

I need something like that ...:

Farm.where(animals.count > 5)  

Update / Answer:

Farm.joins(:animals).group("farm_id").having("count(farm_id) > 5")
+4
source share
2 answers

Try:

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

Link: fooobar.com/questions/168602 / ...

+8
source

Consider using counter_cache in Farm -> Animal

class Farm < ActiveRecord::Base
  has_many :animals
end

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

Do not forget to add animals_count(integer) to the table 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

Find farms with 5 or more animals

Farm.where("farms.animals_count >= 5")
+4
source

All Articles