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
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")
source
share