【问题标题】:Counter Cache on a condition not on associationCounter Cache on a condition not on association
【发布时间】:2014-04-18 16:07:58
【问题描述】:

我已经阅读了有关关联的计数器缓存。

有没有一种方法可以在某些条件下轻松实现(通过一个可以完成繁重工作的 gem)计数器缓存?例如:

通常是计数器缓存

class User
  has_many :messages

class Message
  belongs_to :user, counter_cache: true

但是,假设我不想计算多少条消息,而是计算来自 Joe 的所有消息中的字符总数

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

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

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

有没有办法得到类似上面的东西?

【问题讨论】:

  • 不,没有,你必须自己实现它,例如before_save

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


【解决方案1】:

目前,对此没有特殊的方法/帮助程序。 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 关联。

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 2022-12-02
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多