Rails迁移 - 更改模型的属性名称

时间:2017-11-08 06:19:18

标签: ruby-on-rails postgresql database-migration rails-migrations

Comment的我的Rails模型中,我message属性datecreated_at属性updated_at自动提供属性ActiveRecord::Migration通过t.timestamps

目前,date属性在comments表的db(postgresql)中具有值。我想删除date模型中的Comment属性,同时执行此操作要更新comments属性的created_at db表值,其值为date属性

我该如何解决这个问题?

1 个答案:

答案 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