在Comment
的我的Rails模型中,我message
属性date
,created_at
属性updated_at
自动提供属性ActiveRecord::Migration
通过t.timestamps
。
目前,date属性在comments
表的db(postgresql)中具有值。我想删除date
模型中的Comment
属性,同时执行此操作要更新comments
属性的created_at
db表值,其值为date
属性
我该如何解决这个问题?
答案 0 :(得分:1)
您可以在迁移文件中编写rails代码,如下所示,以更新列值。
假设列date
的数据类型为timestamp
。
class RemoveDateFromComment < ActiveRecord::Migration
def up
Comment.all.each do |comment|
comment.update(created_at: comment.date)
end
remove_column :comments, :date, :timestamp
end
def down
add_column :comments, :date, :timestamp
Comment.all.each do |comment|
comment.update(date: comment.created_at)
end
end
end