计数器缓存在不关联的条件下

时间:2014-04-18 07:08:02

标签: ruby-on-rails ruby ruby-on-rails-3 caching counter-cache

我已经阅读了关于协会的反缓存。

对于某些情况,有没有办法轻松实现(通过一个可以解除繁重的宝石)计数器缓存?例如:

通常是一个计数器缓存

class User
  has_many :messages

class Message
  belongs_to :user, counter_cache: true

然而,让我们说我不想计算多少条消息,而是计算来自Joe的所有消息中的字符总数

所以假设我有一个方法count_chars_from(user),它返回用户的字符数

我希望在系统中发生许多事情时更新特定列(当joe向多个人发送消息时 - 所有这些用户都需要更新,当joe将消息编辑给一个人时等)

我猜这可以通过观察者来完成,但我发现自己很快就会创建丑陋的代码。

有没有办法像上面这样的东西?

1 个答案:

答案 0 :(得分:0)

目前,没有特殊的方法/助手。 Rails不支持条件计数器。

但是,您可以简单地定义自己的。

class Message
  belongs_to :user
  after_create :inc_counters
  after_destroy :dec_counters

  private
  def inc_counters
    if user && your_conditions
      user.increment(:conditional_counter)
    end
  end

  def dec_counters
    if user && your_conditions
      user.decrement(:conditional_counter)
    end
  end
end

我建议您查看counter_cache implementation。它看起来相当复杂,但简单的实现在我的一个项目中很有效 另请考虑使用update_column来触发User模型上的验证和回调 如果父模型在关联时有dependent: :destroy,则在删除父模型时测试代码。