【问题标题】:Rails :counter_cache with custom query associationRails :counter_cache 与自定义查询关联
【发布时间】:2015-02-03 16:25:31
【问题描述】:

我有一个这样的模型:

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 呢?我可以以相同(简单)的方式缓存它们吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord database-performance


    【解决方案1】:

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

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

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

    但基本上你可以添加一些回调到Vote 并自己增加/减少两个自定义计数器。

    【讨论】:

    • counter_culture 非常适合这个!谢谢
    • @ProGM 你能说出你是如何用 counter_culture gem 解决这个问题的吗?
    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多