Cor*_*nne 6 ruby activerecord ruby-on-rails
我有很多Farms,每个农场都有很多animals.我需要找到每个有超过5只动物的农场.
我需要一些与此类似的东西......:
Farm.where(animals.count > 5)
Run Code Online (Sandbox Code Playgroud)
更新/回答:
Farm.joins(:animals).group("farm_id").having("count(farm_id) > 5")
Run Code Online (Sandbox Code Playgroud)
尝试:
Farm.joins(:animals).group("farm.id").having("count(animals.id) > ?",5)
Run Code Online (Sandbox Code Playgroud)
参考:https://stackoverflow.com/a/9370734/429758
考虑在Farm - > Animal上实现counter_cache
class Farm < ActiveRecord::Base
has_many :animals
end
class Animal < ActiveRecord::Base
belongs_to :farm, counter_cache: true
end
Run Code Online (Sandbox Code Playgroud)
不要忘记向表中添加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
Run Code Online (Sandbox Code Playgroud)
寻找有5个或更多动物的农场
Farm.where("farms.animals_count >= 5")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3741 次 |
| 最近记录: |