views:

164

answers:

2

I have a table 'invoices' in my development database (sqlite3) populated with a small amount of test data.

I wanted to add a column 'invoice_number' to it and set up a migration like so:

class AddInvoiceNumberColumnToInvoices < ActiveRecord::Migration
  def self.up
    add_column :invoices, :invoice_number, :integer
  end

  def self.down
    remove_column :invoices, :invoice_number
  end
end

I ran rake db:migrate and it seemed to migrate just fine. However, when I tried to access this column through ActiveRecord it didn't seem to be there. I decided to undo this migration and try again (not sure what I was going to try but I thought I'd start by undoing it) with rake db:migrate VERSION='whatever_the_migration_before_this_one_was_called'. This failed with the error message

==  AddInvoiceNumberColumnToInvoices: reverting ===============================
-- remove_column(:invoices, :invoice_number)
rake aborted!
An error has occurred, this and all later migrations canceled:

altered_invoices.invoice_number may not be NULL

I can't find any documentation of this error. Is anyone able to explain what I have done wrong, and more importantly how I can fix this?

+1  A: 

You are running migrations out of order. Try this series:

rake db:migrate # now invoice_number is available
rake db:migrate:down VERSION=invoice_number_migration # invoice_number is NOT available
rake db:migrate:up VERSION=invoice_number_migration # invoice_number is now available again

Not sure why you couldn't access your column. Check the db, make sure it was created properly.

Jonathan Julian
You can also use rake db:rollback STEP=N to go back N migrations. rake db:reset will drop the database, create the database, and run all the migrations from the beginning.
Fred
Thanks, this didn't fix my problem (even rake db:reset didn't). I ended up deleting the entire database file and starting again. Everything worked this time. I must have made an error somewhere but I never picked it up. Thanks for your help.
brad
A: 

OK, I finally solved this weeks down the track.

I repeatedly encountered this issue and got in the habit of backing up my database before doing any migrations in case I wanted to undo them as this error kept popping up.

The issue was that I had the sqlite3 gem installed instead of the sqlite3-ruby gem. I haven't looked into why this was occurring but the problem went away after doing this;

sudo gem uninstall sqlite3
sudo gem install sqlite3-ruby

FYI I'm running Rails 2.3.5 on Ruby 1.9.1

brad