gpt4 book ai didi

ruby-on-rails - counter_cache 与 has_many :through

转载 作者:数据小太阳 更新时间:2023-10-29 06:29:41 26 4
gpt4 key购买 nike

我刚刚创建了一个 counter_cache 字段, Controller 看起来像这样。

 @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

关于ruby-on-rails - counter_cache 与 has_many :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com