【问题标题】:Rails counter cache with has_many: :through带有 has_many: :through 的 Rails 计数器缓存
【发布时间】:2020-03-07 02:50:01
【问题描述】:

我有一个 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 来执行此操作,但在这种情况下我该怎么做呢?有可能吗?

【问题讨论】:

标签: ruby-on-rails counter-cache


【解决方案1】:

根据评论中的答案,我设法通过这样做来解决它:

  • 将 images_count 列添加到 Parts 并更新迁移中的计数器
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 添加到图库
belongs_to :part, counter_cache: :images_count

【讨论】:

  • 这只会计算画廊。
  • 没有。我验证了这一点,part.images.size == part.images_count
猜你喜欢
  • 1970-01-01
  • 2013-03-21
  • 2019-03-04
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2011-06-06
相关资源
最近更新 更多