Adim
Adim

Reputation: 811

Copy one column in a database table to a different column in the same table in rails

I am trying to do a migration of a column in a table in my database. I have a 'name' field and I want to migrate all the info in the name field to a 'user_name' field. What is the correct way in ruby on rails to copy the values of one column in the user table to another column in the same table?

Upvotes: 3

Views: 1906

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Add the column

add_column :table, :user_name, :string

and then run an update script (in a db console or via execute in a migration file)

update table set user_name = name;

Or, if you don't want to keep the old column, you can just rename it.

rename_column :table, :name, :user_name

rename_column(table_name, column_name, new_column_name): Renames a column but keeps the type and content.

Upvotes: 4

Related Questions