假设我有一个模型
Vehicle
和它
has_many :wheels
什么是正确的发现/:conditions => ...声明只找到有3个或更多轮子的车辆,例如:三轮车,汽车,卡车,坦克等......?
答案 0 :(得分:3)
不一样,但我相信你可以借助这个问题的答案来解决你的问题:Using named_scope with counts of child models
简而言之:
将wheels_count
列添加到您的车辆表
class Wheel < ActiveRecord::Base
belongs_to :vehicle, :counter_cache => true # this will autoupdate the wheels_count on Vehicle
end
现在您可以按车轮数量搜索您的车辆:
# for all Vehicles with 4 Wheels
Vehicle.all(:condition => { :wheels_count => 4 })
# or for all Vehicles with more than 3 Wheels
Vehicle.all(:condition => ["wheels_count > ?", 3])
<强>更新强>
class AddWheelCount < ActiveRecord::Migration
def self.up
add_column :vehicles, :wheels_count, :integer, :default => 0
Vehicle.reset_column_information
Vehicle.all.each do |p|
p.update_attribute :wheels_count, p.wheels.length
end
end
def self.down
remove_column :vehicles, :wheels_count
end
end
所以wheels_count设置为当前计数