我的模型中有一个counter_cache
列。我用acts_as_paranoid
做这个模型(偏执宝石)。当我恢复记录时,如何更新关联记录的计数器缓存列?
您可以使用before_restore
回调。将.increment_counter
方法用于关联的记录放入before_restore
回调中。
reset_counters
方法或+= 1
方法无效
这里有一个模型关注解决这个问题。
如果你遇到这个问题,你应该已经安装了paranoid gem,但为了完整起见,请在你的Gemfile中包含paranoid gem,并使用'bundle'命令安装它。
# Gemfile
gem 'paranoid'
创建一个关注点。
# app/models/concerns/paranoid_deletable.rb
module ParanoidDeletable
extend ActiveSupport::Concern
included do
# activate the paranoid behavior
acts_as_paranoid
# before restoring the record, manually increment the counter
before_restore :increment_counter_cache
end
module ClassMethods
def counter_column_name
"#{self.name.underscore.pluralize}_count"
end
end
def counter_associations
associated_counters = []
# get all belongs_to associations
self.reflect_on_all_associations(:belongs_to).collect do |association|
return unless association.options[:counter_cache]
associated_klass_name = association.options[:polymorphic] ? self.send("#{association.name}_type") : association.class_name
associated_klass_name.constantize.column_names.each do |column_name|
# collect the association names and their classes if a counter cache column exists for this (self) class.
associated_counters << { association_name: association.name, klass_name: associated_klass_name } if(column_name == self.class.counter_column_name)
end
end
# return the array of { association_name, association_klass } hashes
associated_counters
end
private
def increment_counter_cache
# before restore...
self.counter_associations.each do |counter_association|
association_name = counter_association[:association_name]
klass_name = counter_association[:klass_name]
# ...increment all associated counters
klass_name.constantize.increment_counter(self.class.counter_column_name.to_sym, self.send("#{association_name}_id".to_sym))
end
end
end
然后在你的模型。
# app/models/post.rb
class Post < ActiveRecord::Base
include ParanoidDeletable
belongs_to :user, :counter_cache => true
...
end
一些设置注意事项:
1)你的pluralized belongs_to:association_name必须匹配你的计数器缓存列名称:"#{association_name}_count"。例如:
# Will work
console > user.posts_count
=> 212
# Won't work
console > user.how_much_they_talk_count
=> 212
2a)如果你正在使用多态关系,它的关联需要在两个模型中适当地设置。例如:
# app/models/post.rb
....
has_many :comments, as: :commentable
....
# app/models/comment.rb
...
belongs_to :commentable, polymorphic: true, counter_cache: true
...
2b)如果你正在使用多态关系,引用类型字段需要命名如下:"#{association_name}_type"。例如:
# Will work
console > comment.commentable_type
=> "Post"
# Won't work
console > comment.commentable_class_name
=> "Post"
免责声明:我试图使这个模块化,但这是第一次通过,我还没有彻底测试。
这是一个非常简单的解决方案,尽管有些人可能不同意其语义。
module ActiveRecord
# trigger create callbacks for counter_culture when restoring
class Base
class << self
def acts_as_paranoid_with_counter_culture
acts_as_paranoid
simulate_create = lambda do |model|
model.run_callbacks(:create)
model.run_callbacks(:commit)
end
after_restore(&simulate_create)
end
end
end
end
那么您只需将acts_as_paranoid
的调用替换为acts_as_paranoid_with_counter_culture
。