counter_cache 和 has_many :through [英] counter_cache with has_many :through

查看:47
本文介绍了counter_cache 和 has_many :through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚创建了一个 counter_cache 字段,控制器看起来像这样.

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

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

User.rb 中的关联是

The association in User.rb is

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

问题是 counter_cache 是在 Like.rb 的belong_to 中声明的,我不知道如何告诉它是为了 has_many :through 关联.

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

推荐答案

您有上一个

    class Product
      has_and_belongs_to_many :categories
    end

    class Category
      has_and_belongs_to_many :products
    end

和迁移

    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

现在全部改为

    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

和新的

    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

这篇关于counter_cache 和 has_many :through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆