使用 #update_all 更新时间戳 [英] Updating timestamps with #update_all
问题描述
当我有要更新其属性的 id 列表时,数据库中的 updated_at
字段似乎没有改变,这就是我的意思:
When I have list of ids that I want to update their property the updated_at
field in the database doesn't seem to change, here is what I mean :
ids = [2,4,51,124,33]
MyObj.where(:id => ids).update_all(:closed => true)
执行此更新后 updated_at
字段不会更改.但是,当我使用 rails c
进入 rails 控制台并执行此操作时:
After this update is executed updated_at
field doesn't change. However when I enter rails console with rails c
and do this :
obj = MyObj.find(2)
obj.closed = false;
obj.save!
在此语句之后 updated_at
字段更改值.为什么是这样?我在我的应用程序中依赖这个 updated_at
字段,因为我正在侦听更新并在发生这种情况时执行整个应用程序流程?
After this statement updated_at
field changes value. Why is this? I'm relying on this updated_at
field in my app as I'm listening to the updates and doing whole app flow when this happens?
编辑
我刚刚从 dax
中发现:
Timestamps
Note that ActiveRecord will not update the timestamp fields (updated_at/updated_on) when using update_all().
我不想一次更新一条记录,有没有办法解决这个问题?不求助于sql级别?
I don't want to be updating one record at a time, is there a way around this? without resorting to sql level?
推荐答案
#update_all
不实例化模型.
因此,它不会触发回调或验证 - 并且时间戳更新是在回调中进行的.
As such, it does not trigger callbacks nor validations - and timestamp update is made in a callback.
编辑关于
如果你想保留一个查询来统治所有",你可以更新 updated_at 以及 :closed
:
If you want to keep the "one query to rule them all", you can update updated_at as well as :closed
:
MyObj.where(:id => ids).update_all(closed: true, updated_at: DateTime.now)
但请注意验证仍未运行.
But be aware validations are still not run.
这篇关于使用 #update_all 更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!