Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

ruby on rails - counter_cache with has_many :through

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

 @users = User.where(:sex => 2).order('received_likes_count')

The association in User.rb is

 has_many :received_likes, :through => :attachments, :source => :likes, :dependent => :destroy

Problem is that counter_cache is declared in the belong_to of Like.rb and I don't know how to tell it that is for the has_many :through association.

  belongs_to :user, :counter_cache => :received_likes
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...