How To Change the Column Name and Column Type

1.How to change a column name in a migration:

  1. Generate a migration in the console: rails g migration ChangeColumnName
  2. Go to the generated migration file and modify the change method in this way: rename_column :table_name, :old_column, :new_column
  3. class ChangeColumnName < ActiveRecord::Migration[5.0]
  4. def change
  5. rename_column :users, :email, :email_address
  6. end
  7. end
  8. Run rails db:migrate, and don’t forget to update your code with the new name                                                                                                                              NOTICE:
  9. 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.
  10. 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:

  11. Generate a migration in the console: rails g migration ChangeColumnName
  12. Go to the generated migration file and modify the change method in this way: rename_column :table_name, :table_name, :new_type
  13. Run rails db:migrate, and don’t forget to update your code with the new name
  14. class ChangeDateColumnToDatetime < ActiveRecord::Migration[5.0]
  15. def up
  16. change_column :projects, :deadline, :datetime
  17. end
  18. def down
  19. change_column :projects, :deadline, :date
  20. end
  21. .

Comments

Popular posts from this blog

Check Your ageInDays by Javascript