Ruby on rails 执行收集时更新计数器缓存

Ruby on rails 执行收集时更新计数器缓存,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,嗨,我在rails中使用简单的计数器缓存时遇到了问题。我有以下型号: class CarImage < ActiveRecord::Base belongs_to :car, :counter_cache => :images_count end class Car < ActiveRecord::Base has_many :images, :class_name => "CarImage", :dependent => :destroy, :limit

嗨,我在rails中使用简单的计数器缓存时遇到了问题。我有以下型号:

class CarImage < ActiveRecord::Base
  belongs_to :car, :counter_cache => :images_count
end

class Car < ActiveRecord::Base
  has_many :images, :class_name => "CarImage", :dependent => :destroy, :limit => 4
end
执行此操作时会出现问题:

car1.images << car2.images
这两辆车上的图像都没有相应的更新

我在这个主题上找到了这个: 在我的案例中,解决方案是这样的:

class Car < ActiveRecord::Base
  has_many :images, :class_name => "CarImage", :dependent => :destroy, :limit => 4
  after_save :update_counter, :if => :car_id_changed?

  private

  def update_counter
    new_car = Car.find(car_id)
    Car.increment_counter(:images_count, new_car.id)
    if car_id_was.present?
      old_car = Car.find(car_id_was)
      Car.decrement_counter(:images_count, old_car.id)
    end
  end

end
但是-我在问自己-为什么不直接将其构建到rails中?我在文档中找不到关于这个问题的任何信息,对我来说,在rails中使用内置计数器缓存几乎是不可用的,如果它真的是这样的话,它只支持创建和销毁,而不支持更新!有人能很好地解释为什么会这样吗?我真的有必要建立一个回调,并密切关注我自己的关系吗

顺便说一句,我用的是3.1