不一样,但我相信你可以通过回答这个问题来解决你的问题:
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
所以车轮计数设置为当前计数