How To Change the Column Name and Column Type
1.How to change a column name in a migration:
- Generate a migration in the console: rails g migration ChangeColumnName
- Go to the generated migration file and modify the
changemethod in this way: rename_column :table_name, :old_column, :new_column - class ChangeColumnName < ActiveRecord::Migration[5.0]
- def change
- rename_column :users, :email, :email_address
- end
- end
- Run rails db:migrate, and don’t forget to update your code with the new name NOTICE:
- Be careful with the reserved names in Rails or SQL when you rename a columnSomething to look out when you rename a column in Rails: the reserved names. You will run into troubles if you use them, sometimes not right away.
- And there are a LOT of them. Therefore, you can’t rename your database column using ‘group’, ‘image’, ‘set’, ‘open’, etc.
2.How to change a Column Type in a migration:
- Generate a migration in the console: rails g migration ChangeColumnName
- Go to the generated migration file and modify the
changemethod in this way: rename_column :table_name, :table_name, :new_type - Run rails db:migrate, and don’t forget to update your code with the new name
- class ChangeDateColumnToDatetime < ActiveRecord::Migration[5.0]
- def up
- change_column :projects, :deadline, :datetime
- end
- def down
- change_column :projects, :deadline, :date
- end
- .
Comments
Post a Comment