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
.
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.
How do I go about this ?
You can write the rails code inside the migration file as below to update the column value.
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