I wrongly named a column hased_password
instead of hashed_password
.
How do I update the database schema, using migration to rename this column?
I wrongly named a column hased_password
instead of hashed_password
.
How do I update the database schema, using migration to rename this column?
Update - A close cousin of create_table is change_table, used for changing existing tables. It is used in a similar fashion to create_table but the object yielded to the block knows more tricks. For example:
This way is more efficient if we do with other alter methods such as: remove/add index/remove index/add column, eg we can do further like:
Update:
You'll probably want to create a separate migration to do this. (Rename FixColumnName as you will)
Then edit the migration to do your will.
An update for Rails 3.1
While, the
up
anddown
methods still apply. Rails 3.1 receives achange
method that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method"If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again.
You could use
change_table
to keep things a little neater.Thank you,
Luke
&&Turadg
, for bringing up the topic.Then just
db:migrate
as usual or however you go about your business.An update for Rails 4
While creating a
Migration
as for renaming a column, Rails 4 generates achange
method instead ofup
anddown
as mentioned in the above answer. The generatedchange
method is as below :which will create a migration file similar to this :
Some versions of Ruby on Rails support to up/down method to migration and if you have up/down method in your migration, then:
If you have the
change
method in your migration, then:For more information you can move: Ruby on Rails - Migrations or Active Record Migrations.
For Ruby on Rails 4:
If your code is not shared with other one, then best option is to do just
rake db:rollback
then edit your column name in migration andrake db:migrate
. Thats itAnd you can write another migration to rename the column
Thats it.
As an alternative option, if you are not married to the idea of migrations, there is a compelling gem for ActiveRecord which will handle the name changes automatically for you, Datamapper style. All you do is change the column name in your model (and make sure you put Model.auto_upgrade! at the bottom of your model.rb) and viola! Database is updated on the fly.
https://github.com/DAddYE/mini_record
Note: You will need to nuke db/schema.rb to prevent conflicts
Still in beta phases and obviously not for everyone but still a compelling choice (I am currently using it in two non-trivial production apps with no issues)