1

I have a Part model that has_many :images, through: :gallery and I would like to implement counter_cache to store the images count of a part. This is my setup.

Part

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

Gallery

belongs_to :part
has_many :images

Image

belongs_to :gallery

I can do @part.images to fetch images of a part and now I would like to cache images count so I can do @part.images.size or even order parts by images_count. I would normally do this using counter_cache: true on a belongs_to side but how do I do this in this case? Is it possible?

jedi
  • 2,003
  • 5
  • 28
  • 66

1 Answers1

0

Based on the answer from the comment I managed to solve it by doing it like this:

  • add images_count column to Parts and update counters in the migration
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
  • add counter_cache: :images_count to Gallery
belongs_to :part, counter_cache: :images_count
jedi
  • 2,003
  • 5
  • 28
  • 66