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

时间:2022-02-04 00:13:19

In my Rails model for Comment, I have attributesmessage, date attributes along created_at and updated_at attributes automatically provided by ActiveRecord::Migration via t.timestamps.

在我的Rails模型中,我有一些属性消息,date_at和updated_at属性的日期属性由ActiveRecord :: Migration通过t.timestamps自动提供。

Currently the date attribute has values in db ( postgresql ) for comments table. I want to remove the date attribute in Comment model and while doing this want to update the comments db table values for created_at attribute with value in date attribute.

目前,date属性的值为db(postgresql),用于comments表。我想在Comment模型中删除date属性,并且这样做时想要使用date属性中的值更新created_at属性的注释db表值。

How do I go about this ?

我该怎么做?

1 个解决方案

#1


1  

You can write the rails code inside the migration file as below to update the column value.

您可以在迁移文件中编写rails代码,如下所示,以更新列值。

Assuming datatype of column date is 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

#1


1  

You can write the rails code inside the migration file as below to update the column value.

您可以在迁移文件中编写rails代码,如下所示,以更新列值。

Assuming datatype of column date is 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