gpt4 book ai didi

ruby-on-rails - 覆盖 rails update_all 方法

转载 作者:行者123 更新时间:2023-12-04 06:11:41 25 4
gpt4 key购买 nike

我需要重写 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com