问题描述
如果您有 DB 列 created_at
和 updated_at
Rails 将在您创建和更新模型对象时自动设置这些值.有没有办法在不触及这些列的情况下保存模型?
If you have DB columns created_at
and updated_at
Rails will automatically set those values when you create and update a model object. Is there a way to save the model without touching those columns?
我引入了一些遗留数据,我想根据(不同名称的)遗留数据字段中的相应值设置这些值.我发现当我在模型上设置它们然后保存模型时,Rails 似乎覆盖了传入的值.
I am bringing in some legacy data and I would like to set those values from the corresponding values in the (differently named) legacy data fields. I'm finding when I set them on the model and then save the model, Rails appears to override the incoming values.
当然,我可以对 Rails 模型列进行不同的命名以防止出现这种情况,但在导入数据后,我希望 Rails 自动执行时间戳操作.
Of course I could just name the Rails model columns differently to prevent that, but after the data is imported, I want Rails to do its automatic timestamp thing.
推荐答案
在迁移或 rake 任务中执行此操作(或在 新的数据库种子(如果你在边缘轨道上):
Do this in a migration or in a rake task (or in the new database seeds if you're on edge rails):
ActiveRecord::Base.record_timestamps = false
begin
run_the_code_that_imports_the_data
ensure
ActiveRecord::Base.record_timestamps = true # don't forget to enable it again!
end
您可以安全地手动设置 created_at
和 updated_at
,Rails 不会抱怨.
You can safely set created_at
and updated_at
manually, Rails won't complain.
注意:这也适用于单个模型,例如User.record_timestamps = false
Note: This also works on individual models, e.g. User.record_timestamps = false
这篇关于有没有办法避免自动更新 Rails 时间戳字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!