Thursday, January 24, 2013

Create PostgreSQL Sequence for Ruby on Rails Apps on Heroku

I was attempting to add a record via my rails app on Heroku and got the following:
ERROR: null value in column "id" violates not-null constraint

Since as the date of this writing Heroku uses PostgreSQL, here are the steps I took.

My Postgres server version is PostgreSQL 9.1.7 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3, 64-bit. I also am using an Ubuntu Linux desktop running Rails 3.2.11.

Now to the steps I took to solve the problem.

In your rails app db/migrate folder create the following class and name it 201301081552_create_table_name_sequence.rb. Substitute the time signature in the name with your date and time and “table_name” with the name of the table you to which you are adding the sequence:

Then in your rails app db/migrate folder create the following class and name it 201301081552_add_sequence_to_table_name.rb. Again, substitute the time signature in the name with your date and time and “table_name” with your name:

Next, commit and push them to your github repository. After that push them to Heroku. If you have the Heroku toolbelt installed you can issue the following:
sudo heroku run rake db:migrate

This should run the database migration that will create the sequence as well as add it to the id column.