I recently modified the customer_number field in my Users table in a
migration:
remove_column :users, :customer_number
execute “CREATE SEQUENCE user_customer_number_seq MINVALUE 10000;”
execute "ALTER TABLE users ADD customer_number integer " +
“DEFAULT nextval(‘user_customer_number_seq’) NOT NULL UNIQUE;”
I want the default value (next in sequence) to be used when I create a
new user. I thought Rails would handle this, but instead I’m getting:
PGError: ERROR: null value in column “customer_number” violates
not-null constraint
I want to keep the NOT NULL constraint. I thought about something like
this:
before_validation_on_create :set_customer_number
def set_customer_number
cust_no = next_sequence_value(‘user_customer_number_seq’)
self.customer_number = cust_no
end
Although that’s not quite right. next_sequence_value is not defined in
the Postgres adapter. How would I write set_customer_number? Or would
removing the null constraint and relying on validates_presence_of
:customer_number be enough?
Chris S. wrote:
I recently modified the customer_number field in my Users table in a
migration:
remove_column :users, :customer_number
execute “CREATE SEQUENCE user_customer_number_seq MINVALUE 10000;”
execute "ALTER TABLE users ADD customer_number integer " +
“DEFAULT nextval(‘user_customer_number_seq’) NOT NULL UNIQUE;”
I want the default value (next in sequence) to be used when I create a
new user. I thought Rails would handle this, but instead I’m getting:
PGError: ERROR: null value in column “customer_number” violates
not-null constraint
I want to keep the NOT NULL constraint. I thought about something like
this:
before_validation_on_create :set_customer_number
def set_customer_number
cust_no = next_sequence_value(‘user_customer_number_seq’)
self.customer_number = cust_no
end
Although that’s not quite right. next_sequence_value is not defined in
the Postgres adapter. How would I write set_customer_number? Or would
removing the null constraint and relying on validates_presence_of
:customer_number be enough?
Ok, figured it out:
def set_customer_number
customer_number_sequence = ‘user_customer_number_seq’
cust_no = connection.select_value(“select
nextval(’#{customer_number_sequence}’)”)
self.customer_number = cust_no
end
Actually ended up getting rid of the null constraint, but I still need
the above for validation in one of my models.