AASM이있는 다중 카운터 캐시 열
-
21-08-2019 - |
문제
각 상태의 수를 캐시하는 방법을 찾고 있습니다. 이전에 카운터 캐싱을 수행했지만 각 상태에 대해 여러 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 개의 열인 것 같습니다. 어떤 아이디어?
해결책
각 상태마다 하나씩 하나의 열을 수행해야하지만 더티 객체 기능을 사용하여 해당 카운터를 증가/감소시키기 위해 수동으로 로직을 작성해야합니다. 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
(이 코드는 테스트되지 않았지만 이것은 기본 아이디어입니다)
제휴하지 않습니다 StackOverflow