Active record, postgresql sequences and primary keys

Hello all.
I have a question about using active record and postgresql sequences.

My environment is:
Ruby: ruby-1.9.2-p290 [ x86_64 ]
Rails: 3.1.1.
PostgreSQL: 9.0.5.
pg: 0.11.0.

I have a very simple table:

CREATE TABLE accounts
(
id bigint NOT NULL,
username character(255)
)

and I have a simple script for connect to DB:

require “rubygems”
require “active_record”

ActiveRecord::Base.establish_connection(
:adapter => “postgresql”,
:host =>“localhost”,
:username => “test”,
:password => “”,
:database => “project_development”
)

class Account < ActiveRecord::Base
set_sequence_name “account_seq”
set_primary_key :id
end

account = Account.new
account.username = “User1”
account.save


Task: I want use postgresql sequence for generation of primary key.
I use ‘set_sequence_name’, but this don’t work.

Question: How to make active use of the active record of the sequence
to generate a primary key?

On Friday, October 21, 2011 2:57:56 PM UTC-4, Ruby-Forum.com User wrote:

Task: I want use postgresql sequence for generation of primary key.
I use ‘set_sequence_name’, but this don’t work.

What part of it does not work? Are you getting any error messages?

When I save account, id = null, and postgresql swears that id is null.
I have id field:
id bigint NOT NULL,

I want that active record invoke sequence and insert new primary key to
id property.

I have changed accounts table and add constraints:

CREATE TABLE accounts
(
id bigint NOT NULL,
username character(255),
CONSTRAINT c_accounts_pkey PRIMARY KEY (id),
CONSTRAINT u_accounts_id UNIQUE (id)
)

account_seq DDL:

CREATE SEQUENCE account_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;

But active record don’t use account_seq again :(.

On 22 October 2011 09:05, Eugene B. [email protected] wrote:

I have change type of ID: bigint → to serial and all work now.
But my legacy DB has id as bigint.
How can I invoke sequence from code?

I don’t know the full answer, but I think you may have to use
set_primary_key in your model. Google for rails legacy database and
you may find some helpful links.

Colin

I have change type of ID: bigint -> to serial and all work now.
But my legacy DB has id as bigint.
How can I invoke sequence from code?