I am developing (currently) a Rails 2.3.x application with a PostgreSQL 8.4 database backend. In my Rails application, I have a model corresponding to a database table that has two columns of the SERIAL data type and is set to NOT NULL. I have one of these columns defined as the primary key in Rails and as a restriction of PostgreSQL.
Table definition:
CREATE TABLE problem_table ( col1 serial NOT NULL, col2 serial NOT NULL, other_col1 character varying, other_col2 character varying, ..., CONSTRAINT problem_table_pkey PRIMARY KEY (col1) );
Model class definition:
class ModelClass1 < ActiveRecord::Base self.table_name = 'problem_table' self.primary_key = 'col1' end
My problem is with SERIAL NOT NULL column with non-primary key. When I try to create Rails ActiveRecord :: Base # create, Rails rightfully does not set the value of the SERIAL NOT NULL column of the primary key, but sets the value of the NULL column to another, which causes PostgreSQL to complain that the NOT NULL column is set to NULL.
What will I say to Rails:
ModelClass1.create( other_col1: 'normal' other_col2: 'data', ... );
What Rails tells PostgreSQL:
INSERT INTO problem_table ( col2, other_col1, other_col2, ... ) VALUES ( NULL, 'normal', 'data', ... );
My question is, how can I get Rails to stop passing NULL for this column and just not skip anything by letting DEFAULT nextval (my_seq) take over? Or, if this is not possible, how can I tell PostgreSQL to ignore this NULL value when passing and / or recognize it the same way as "set as DEFAULT"?
I would try just the monkey patch Rails 2.3.x ActiveRecord, but I know that if I did this, I would screw it when the transition to Rails 3 comes.
I was looking for an attempt to fix things with the PL / pgSQL trigger before INSERT, but I can't figure out how to tell PostgreSQL that PL / pgSQL is βundefineβ is NEW.col2 or say NEW.col2: = DEFAULT (which doesn't work).
Answers and / or suggestions are welcome!