counter_cache with has_many :through

前端 未结 3 1203
温柔的废话
温柔的废话 2020-11-30 04:59

I just created a counter_cache field and the controller looks like this.

 @users = User.where(:sex => 2).order(\'received_likes_count\')
<
3条回答
  •  旧时难觅i
    2020-11-30 05:29

    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
    

提交回复
热议问题