Notes on Learning Rails part2
How to change your database tables? Use a migration – it’s easy!
While building you first Rails app, you’re more than likely to change the design of your database tables a few times. For example I suddenly decided that I wanted some columns on of my tables to be foreign keys to another database. In any other language this would be as simple as writing a bit of SQL to change the column names. Actually if it wasn’t for Rails needing to know when you use foreign keys, you wouldn’t even have to change the names, but Rails needs them to have _id at the end of the table column name just so it can pick up on your database structure.
Anyway… this is how you do it.
First get out of the rails console if you are in it, we don’t need to be in there for this.
1. in your project directory run the command:
rails generate migration change_my_column_name_migrationThe more descriptive you can be with your migration name, the better. I generally opt for longer, more descriptive names for things that I am only going to use once or twice. This is one of those cases, you’ll only have to type it out once more.
2. open up the file that it created: db/migrate/2423(timestamp)0000_migration_name.rb
3. in the self.up method, put this:
rename_column :table_name, :the_old_column_name, :the_new_column_nameFor my case i was just adding “_id” to the end of my column name, so here’s an example of what I used
4. You’ll want to make a reciprocal statement in the self.down method so rails can rollback if it needs to.
Here’s what my entire migration file looked like:
class ChangeCurrencyColumnName < ActiveRecord::Migrationdef self.up
rename_column :trades, :trade_currency, :trade_currency_id
end def self.down
rename_column :trades, :trade_currency_id, :trade_currency
end
end
5. Save your file and go back to the command prompt. Enter the following command:
rake db:migrate
6. Your done!
I find that this solution is easier than trying to rollback, edit an existing migration file, then rerun the existing migration. Editing existing migrations may erase your embarrassing mistakes in the past, but having loads of migration files sitting around is pretty common for any large rails app. So you might as well get used it.