I absolutely loves Rails 2.0 and the command line conveniences it provides for the RESTful scaffolding and models. Here’s a couple of tricks to generate a migration to quickly to add/remove columns from an existing table.
Assume you already have a table called ‘Users’. You would like to add a column called ‘title’ and another column called ‘email’. You can quickly create a migration from the command line using the following :
script/generate migration AddTitleEmailToUsers title:string email:string
The migration generated looks like this:
class AddTitleEmailToUsers < ActiveRecord::Migration
def self.up
add_column :users, :title, :string
add_column :users, :email, :string
end
def self.down
remove_column :users, :email
remove_column :users, :title
end
end
</pre>
And if you need to remove those same columns, you can generate a migration with the following :
script/generate migration RemoveTitleEmailFromUsers title:string email:string
The title of the migration is significant. The beginning Add/Remove specifies the action to take, the To/From specifies the tablename to apply the action against.
How sweet is that?!?
June 13th, 2008 at 5:47 am
Hi Jim,
I’m trying to add a “Date available” column to a “products” table, but after I type in the commands like what you have above, its not showing in the db or browser.
Here’s what I typed and got back:
ruby script/generate migration AddDate_availableToProducts date_available:datetime
exists db/migrate
create db/migrate/20080613112844_add_date_available_to_products.rb
Then I ran rake db:migrate to update the db, but its not updating.
The db/migrate file seems to have been updated correctly too:
class AddDateAvailableToProducts
June 13th, 2008 at 5:51 am
continued…
def self.up
add_column :products, :date_available, :datetime
end
def self.down
remove_column :products, :date_available
end
end
But the browser just shows the existing db fields without adding the Date Available column. Any idea where I am going wrong? Thanks.
June 13th, 2008 at 8:32 am
@Peter -
You mean your product form isn’t reflecting the added column? You would need to manually update your views to facilitate the newly added column.
June 15th, 2008 at 10:14 am
Thanks for your help Jim.
I had some errors updating the views, but got the extra column to show by destroying the existing scaffolding and generating a new one of the same name.
Very useful post you have here by the way, its really helped my along my way. Thanks!
June 15th, 2008 at 10:15 am
Sorry, I should have clarified in my post - yes, the problem was that my product form wasn’t reflecting the added column.
Cheers - Peter