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")
Try:
Farm.joins(:animals).group("farm.id").having("count(animals.id) > ?",5)
Ref: https://stackoverflow.com/a/9370734/429758
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With