我需要覆盖 rails (活动记录)update_all
方法,以便它也总是更新updated_at
字段。我应该如何实现这一目标?
问问题
982 次
2 回答
7
将以下代码放入文件中/config/initializers/update_all_with_touch.rb
class ActiveRecord::Relation
def update_all_with_touch(updates, conditions = nil, options = {})
now = Time.now
# Inject the 'updated_at' column into the updates
case updates
when Hash; updates.merge!(updated_at: now)
when String; updates += ", updated_at = '#{now.to_s(:db)}'"
when Array; updates[0] += ', updated_at = ?'; updates << now
end
update_all_without_touch(updates, conditions, options)
end
alias_method_chain :update_all, :touch
end
:updated_at => Time.now
每当您使用时,它都会自动添加参数update_all
。
解释:
此代码段用于alias_method_chain
覆盖默认值update_all
:
alias_method_chain :update_all, :touch
方法update_all
替换成update_all_with_touch
我定义的方法,原来update_all
的改名为update_all_without_touch
. 新方法修改upgrades
对象以注入 的更新updated_at
,然后调用原始的update_all
。
于 2013-09-29T12:29:01.253 回答
2
You can override the update_all method in your model:
def self.update_all(attr_hash) # override method
attr_hash[:updated_at] = Time.now.utc
super( attr_hash )
end
于 2013-09-29T10:29:17.617 回答