Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 非关联条件下的计数器缓存_Ruby On Rails_Ruby_Ruby On Rails 3_Caching_Counter Cache - Fatal编程技术网

Ruby on rails 非关联条件下的计数器缓存

Ruby on rails 非关联条件下的计数器缓存,ruby-on-rails,ruby,ruby-on-rails-3,caching,counter-cache,Ruby On Rails,Ruby,Ruby On Rails 3,Caching,Counter Cache,我读过关于协会的计数器缓存 有没有一种方法可以在某些情况下轻松实现(通过一个gem来完成繁重的工作)计数器缓存?例如: 通常,计数器缓存是 class User has_many :messages class Message belongs_to :user, counter_cache: true 但是,假设我不想计算有多少条消息,而是要计算来自Joe的所有消息中的字符总数 假设我有一个方法count\u chars\u from(user),它返回用户的字符数 当系统中发生很多

我读过关于协会的计数器缓存

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

通常,计数器缓存是

class User
  has_many :messages

class Message
  belongs_to :user, counter_cache: true
但是,假设我不想计算有多少条消息,而是要计算来自Joe的所有消息中的字符总数

假设我有一个方法
count\u chars\u from(user)
,它返回用户的字符数

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

我想这可以通过观察者来完成,但我看到自己很快就创建了难看的代码


有没有一种方法可以实现上述功能?

目前,没有专门的方法/帮助。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
我建议你去看看。它看起来相当复杂,但在我的一个项目中,简单的实现非常有效。
也可以考虑使用<代码> UpDeaTeField> /Cult>不触发对<代码>用户< /代码>模型的验证和回调。
并在删除父模型时测试您的代码,如果父模型有关联
dependent::destroy

没有,您必须自己实现它,例如,在保存之前