Rails :counter_cache 与自定义查询关联

Rails :counter_cache with custom query association

我有这样一个模型:

class Vote
  belongs_to :content, counter_cache: true
end

class Content
  has_many :votes
  has_many :votes_up, -> { where(positive: true) }, class_name: 'Vote'
  has_many :votes_down, -> { where(positive: false) }, class_name: 'Vote'
end

如果我创建正确的迁移,当我执行 mycontent.votes_count 时,它不会进行查询。

但是 mycontent.votes_up.countmycontent.votes_down.count 呢?我可以用相同(简单)的方式缓存它们吗?

我不知道开箱即用的 rails 解决方案,所以我认为它需要一些自定义代码。它应该非常简单,只涉及向 Vote 添加一些回调和向 Content 添加两个缓存列。您可以在此处查看可用的回调:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

我认为在 Vote 中添加 after_saveafter_destroy 就可以了。

您也可以看看这个 gem:https://github.com/magnusvk/counter_culture 它可能会有帮助。

但基本上您可以自己添加一些回调到 Vote 和 increment/decrement 两个自定义计数器。