使用 aasm 的多个计数器缓存列

发布于 2024-07-25 08:08:14 字数 446 浏览 6 评论 0原文

我正在寻找一种方法来缓存每个状态的数量。 我以前做过计数器缓存,但是有没有办法为每个状态创建多个 counter_cache 列并保持它们更新,或者我应该在其他地方寻找缓存这些值。

aasm_column :state
aasm_initial_state :unopened

aasm_state :unopened
aasm_state :contacted
aasm_state :closed

aasm_event :contact do
  transitions :to => :contacted, :from => [:unopened] 
end

aasm_event :close do
  transitions :to => :closed, :from => [:contacted] 
end

看起来数据库中只有 3 列。 有任何想法吗?

I am looking for a way to cache the number of each state. I have done counter caching before, but is there a way to create multiple counter_cache columns for each state and keep them updated or should I look elsewhere for caching these values.

aasm_column :state
aasm_initial_state :unopened

aasm_state :unopened
aasm_state :contacted
aasm_state :closed

aasm_event :contact do
  transitions :to => :contacted, :from => [:unopened] 
end

aasm_event :close do
  transitions :to => :closed, :from => [:contacted] 
end

It seems like it would just be 3 columns in the database.
Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Spring初心 2024-08-01 08:08:14

您必须执行三列,每个状态一列,但使用脏对象功能手动编写逻辑来递增/递减这些计数器。 Rails 在 save 中不提供任何自动逻辑来执行此操作。

所以在被统计的模型中:(

after_create :increment_counter
after_save :update_counters
after_destroy :decrement_counter

def increment_counter
  self.parent.increment("#{self.state}_counter")
end

def decrement_counter
  self.parent.decrement("#{self.state}_counter")
end

def update_counters
  return unless self.state_changed?
  self.parent.decrement("#{self.state_was}_counter")
  self.parent.increment("#{self.state}_counter")
end

这段代码未经测试,但这是基本思想)

You would have to do three columns, one for each state, but write logic manually to increment/decrement those counters, using dirty object functionality. Rails doesn't provide any automatic logic in save to do this.

So in the model being counted:

after_create :increment_counter
after_save :update_counters
after_destroy :decrement_counter

def increment_counter
  self.parent.increment("#{self.state}_counter")
end

def decrement_counter
  self.parent.decrement("#{self.state}_counter")
end

def update_counters
  return unless self.state_changed?
  self.parent.decrement("#{self.state_was}_counter")
  self.parent.increment("#{self.state}_counter")
end

(This code is untested, but this is the basic idea)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文