gpt4 book ai didi

ruby-on-rails - 使用#update_all 更新时间戳

转载 作者:数据小太阳 更新时间:2023-10-29 06:34:06 25 4
gpt4 key购买 nike

当我有要更新其属性的 ID 列表时,数据库中的 updated_at 字段似乎没有改变,这就是我的意思:

ids = [2,4,51,124,33]
MyObj.where(:id => ids).update_all(:closed => true)

执行此更新后,updated_at 字段不会更改。但是,当我使用 rails c 进入 rails 控制台并执行此操作时:

obj = MyObj.find(2)
obj.closed = false;
obj.save!

在此语句之后 updated_at 字段更改值。为什么是这样?当发生这种情况时,我正在监听更新并执行整个应用程序流程时,我依赖于我的应用程序中的这个 updated_at 字段吗?

编辑

我刚从 dax 的答案中发现:

Timestamps

Note that ActiveRecord will not update the timestamp fields (updated_at/updated_on) when using update_all().

我不想一次更新一条记录,有没有办法解决这个问题?不求助于 sql 级别?

最佳答案

#update_all does not instantiate models .

因此,它不会触发回调或验证 - 时间戳更新是在回调中进行的。

编辑关于编辑:

如果你想保留“一个查询来统治它们”,你可以更新 updated_at 以及 :closed :

MyObj.where(:id => ids).update_all(closed: true, updated_at: DateTime.now)

但请注意,验证仍未运行。

关于ruby-on-rails - 使用#update_all 更新时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18873125/

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