Ruby on Rails: adding columns to existing database

hellomello picture hellomello · Apr 28, 2013 · Viewed 37k times · Source

I'm getting an error:

SQLite3::SQLException: no such column: ideas.list_id: 
SELECT "ideas".* FROM "ideas"  
WHERE "ideas"."list_id" = 2

But I added

t.integer :list_id

to my db migration file:

class CreateIdeas < ActiveRecord::Migration
  def change
    create_table :ideas do |t|
      t.string :name
      t.text :description
      t.string :picture

      t.timestamps
    end
    add_foreign_key :ideas, :lists
  end
end

which gave me this:

class CreateIdeas < ActiveRecord::Migration
  def change
    create_table :ideas do |t|
      t.string :name
      t.text :description
      t.string :picture
      t.integer :list_id
      t.timestamps
    end
    add_foreign_key :ideas, :lists
  end
end

and then I typed

rake db:migrate

Any idea why I would be getting an error saying there's no column? I'm still new to RoRs. Do I have to add a column some other way?

Thanks

Answer

amb110395 picture amb110395 · Apr 28, 2013

As Speransky suggested, you should never modify old migration files. Rather you should create a new migration that adds the desired column. For instance, in this case you would run the following command in your app to create the new migration:

rails generate migration AddListIdColumnToIdeas list_id:integer

And Rails would generate the migration file automatically and the only thing left to do is run rake db:migrate.

If you insist on modifying the old migration file, you can add the column as you did and run the following:

rake db:drop
rake db:create
rake db:migrate

Which will destroy your current database, create a new one and run all the migrations (which will include your new column).