【问题标题】:counter_cache for multi level associationcounter_cache 用于多级关联
【发布时间】:2023-03-08 10:38:01
【问题描述】:

我有 3 个模型:TopicPostLink

class Topic < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  has_many :links
  belongs_to :topic
end

class Link < ActiveRecord::Base
  belongs_to :post
end

我想要counter_cache 用于Link 模型的论坛。 我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    查看counter_culture gem

    来自readme

    class Product < ActiveRecord::Base
      belongs_to :sub_category
      counter_culture [:sub_category, :category]
    end
    
    class SubCategory < ActiveRecord::Base
      has_many :products
      belongs_to :category
    end
    
    class Category < ActiveRecord::Base
      has_many :sub_categories
    end
    

    在上面的示例中,Category 模型将在categories tableproducts_count 列中保留一个最新的计数器缓存。

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多