From: Jason Foreman Date: 2005-08-27T06:24:24+09:00 Subject: Re: probably a stupid rails question On 8/26/05, tsuraan wrote: > I'm working through the Rails intro on > http://www.onlamp.com/pub/a/onlamp/2005/01/20/rails.html, and having a > bit of a problem with the part on page three, where you add a recipe > to the database. My recipes table (in Postgresql) looks like this: > >
>               Table "public.recipes"
>     Column    |          Type          | Modifiers
> --------------+------------------------+-----------
>  id           | integer                | not null
>  title        | character varying(255) | not null
>  description  | character varying(255) |
>  date         | date                   |
>  instructions | text                   |
> Indexes:
>     "recipes_pkey" PRIMARY KEY, btree (id)
> 
> > When I go to add an entry using the Rails structure, I get the following error: > > > ActiveRecord::StatementInvalid in Recipe#create > > > > ERROR: null value in column "id" violates not-null constraint > > : INSERT INTO recipes ("title", "date", "description", "instructions") VALUES('Cookies', > > '2005-08-22', 'Good Stuff', 'I like cookeis a lot. > > Mix the ingredient, and cook them. > > > > yay! > > ') > > > > script/server:49 > > So, it's looking like Rails isn't properly handling the primary key > constraint on the table. Is rails supposed to do this, or should I > ditch the primary key in the database? I don't know much about > databases or about rails, so I'm probably missing something really > obvious. Any ideas? > > 1) It would be better to use the Rails mailing list for your Rails questions. [1] 2) you need to define a sequence and set the default value of that column to the nextval of the sequence. This is in PosgreSQL accomplished by using the 'serial' type when creating the table. create table foo (id serial primary key, ...); You can also go back and do it manually by creating a sequence and altering the table. This is basically equivalent to an 'autoincrement' column in MySQL (not exactly, but similar principle). Jason [1] http://lists.rubyonrails.org/mailman/listinfo/rails