问题描述
如果您有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的做它的自动时间戳的事情prevent。
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.
推荐答案
在迁移或耙子任务(或的的,如果你是在边缘轨道):
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的时间戳字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!