使用has_many::through的Rails计数器缓存



我有一个零件模型,has_many :images, through: :gallery和我想实现counter_cache来存储零件的图像计数。这是我的设置。

部件

has_one :gallery, dependent: :destroy
has_many :images, through: :gallery

画廊

belongs_to :part
has_many :images

图像

belongs_to :gallery

我可以执行@part.images来获取零件的图像,现在我想缓存图像计数,这样我就可以执行@part.images.size,甚至可以通过images_count订购零件。我通常会在belongs_to侧使用counter_cache: true来执行此操作,但在这种情况下我该如何执行?有可能吗?

根据评论的答案,我通过这样做解决了问题:

  • 将images_count列添加到部件并更新迁移中的计数器
class AddImagesCountToParts < ActiveRecord::Migration[5.1]
def change
add_column :parts, :images_count, :integer, default: 0, null: false
Part.find_each { |part| Part.reset_counters(part.id, :images) }
end
end
  • 将counter_cache::images_count添加到Gallery
belongs_to :part, counter_cache: :images_count

最新更新