我需要重写 Rails(事件记录)update_all
方法,以便它也始终更新 updated_at
字段。我应该如何实现这一目标?
最佳答案
将以下代码放入文件/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
每当您使用 update_all
时,它会自动添加参数 :updated_at => Time.now
。
解释:
此代码段使用 alias_method_chain
覆盖 update_all
的默认值:
alias_method_chain :update_all, :touch
方法update_all
被我定义的方法update_all_with_touch
替换,原来的update_all
重命名为update_all_without_touch
。新方法修改了upgrades
对象注入(inject)updated_at
的更新,接下来调用原来的update_all
。
关于ruby-on-rails - 覆盖 rails update_all 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076886/