覆盖rails update_all方法 [英] Override rails update_all method
问题描述
我需要重写rails(活动记录) update_all
方法,以便它始终将 updated_at
字段更新为好。我应该如何实现这一目标?
I need to override the rails (active record) update_all
method so that it always updates the updated_at
field as well. How should I go about achieving this?
推荐答案
将以下代码放入文件 /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 =>每当您使用
。 update_all
的Time.now
It automatically adds the parameter :updated_at => Time.now
whenever you use 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
。新方法修改了升级
对象以注入 updated_at
的更新,然后调用原始的 update_all
。
The method update_all
is replaced by the method update_all_with_touch
I've defined, and the original update_all
is renamed update_all_without_touch
. The new method modifies the upgrades
object to inject the update of updated_at
, and next call the original update_all
.
这篇关于覆盖rails update_all方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!