用于多级关联的counter_cache

时间:2016-07-12 16:50:22

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

我有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。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

查看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模型会在products_count的{​​{1}}列中保留最新的计数器缓存。