我刚刚创建了一个 counter_cache 字段,控制器如下所示。
@users = User.where(:sex => 2).order('received_likes_count')
User.rb 中的关联是
has_many :received_likes, :through => :attachments, :source => :likes, :dependent => :destroy
问题是 counter_cache 是在 Like.rb 的Belong_to 中声明的,我不知道如何告诉它这是针对 has_many :through 关联的。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)