Slinky
Slinky

Reputation: 5832

Alter Schema in Rails 2

I need to add some columns to a table in my schema. Can someone tell me the best way to do this?

The following seems incomplete or wrong since the schema.rb file did not update to include the new column and all of the corresponding view files (edit,index,new,show) did not update to include the new column. Not to mention the bloat of all of those migration classes that get generated. Thanks

ruby script/generate migration RecordLabelToAlbums record_label:string
      exists  db/migrate
      create  db/migrate/20121130125859_record_label_to_albums.rb

Creates this:

class RecordLabelToAlbums < ActiveRecord::Migration
def self.up
end

def self.down
 end
end

I then added this:

class RecordLabelToAlbums < ActiveRecord::Migration
def self.up
   add_column :albums, :record_label, :text
end

def self.down
   remove_column :albums, :record_label
end

end

The I ran:

rake db:migrate

Got This: Mysql::Error: Table 'albums' already exists: CREATE TABLE albums (id int(11) DEFAULT NULL auto_increment PRIMARY KEY, created_at datetime, updated_at datetime)

Upvotes: 0

Views: 186

Answers (1)

Tom Harrison
Tom Harrison

Reputation: 14068

The code you added is correct.

The error suggests that for some reason your system appears to think it has not yet run the original migration that created the albums table. The state of migrations (in Rails 2) is specified in a table in the database called schema_migrations -- if this gets confused then it will try to re-run migrations. I am not sure what might cause it to get confused, but I do recall this happened a couple times back in 2008 when I was using Rails 2.x.

The table is simple -- you can see what's in it from a SQL prompt -- just the names of migrations it thinks it has run, I think.

If you don't mind losing some data, you can try rake db:rollback or even rake db:reset to get back to the beginning. rake db:rollback STEP=2 will rollback the last 2 migrations.

If you need the data, correct the contents of the table by adding one or more new records referencing the migrations in app/db/migrations that may have been missed. The order is important, I think (the format changed a little in Rails 3, I don't recall how).

Any time you want to add or change the database schema, use rails to generate a migration, and then run rake db:migrate once it's ready to go.

And just asking: is there any way you can move to Rails 3. It's been out for years now, and Rails 4 is coming soon. You'll find yourself in a backwater of incompatibilities, deprecations, security and performance issues and so on if you don't take the hit and upgrade.

Upvotes: 1

Related Questions