counter_cache with has_many :through

You have previous

    class Product
      has_and_belongs_to_many :categories
    end

    class Category
      has_and_belongs_to_many :products
    end

and migration

    class CreateCategoriesProducts < ActiveRecord::Migration
      def change
        create_table :categories_products, id: false do |t|
          t.references :category
          t.references :product
        end

        add_index :categories_products, [:category_id, :product_id]
      end
    end

now change all to

    class Product
      has_many :categories_products, dependent: :destroy
      has_many :categories, through: :categories_products
    end

    class Category
      has_many :categories_products, dependent: :destroy
      has_many :products, through: :categories_products
    end

and new one

    class CategoriesProduct < ActiveRecord::Base
      # this model uses table "categories_products" as it is
      # column products_count is in the table "categories"
      belongs_to :category, counter_cache: :products_count
      belongs_to :product
    end

Leave a Comment