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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CreateTableNameSequence < ActiveRecord::Migration | |
def up | |
#create sequence for categories table | |
execute <<-SQL | |
CREATE SEQUENCE table_name_id_seq | |
INCREMENT 1 | |
MINVALUE 1 | |
MAXVALUE 9223372036854775807 | |
START 25 | |
CACHE 1; | |
SQL | |
end | |
def down | |
DROP SEQUENCE table_name_id_seq; | |
end | |
end |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AddSequenceToTableName < ActiveRecord::Migration | |
def up | |
#add sequence to | |
execute <<-SQL | |
ALTER TABLE table_name ALTER COLUMN id SET DEFAULT nextval('table_name_id_seq'::regclass); | |
SQL | |
end | |
def down | |
execute <<-SQL | |
ALTER TABLE table_name ALTER COLUMN id SET NOT NULL; | |
SQL | |
end | |
end |
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.
This should run the database migration that will create the sequence as well as add it to the id column.