Active record, postgresql sequences and primary keys

44 views
Skip to first unread message

Eugene B.

unread,
Oct 21, 2011, 2:57:56 PM10/21/11
to rubyonra...@googlegroups.com
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?

--
Posted via http://www.ruby-forum.com/.

Tim Shaffer

unread,
Oct 21, 2011, 3:14:18 PM10/21/11
to rubyonra...@googlegroups.com
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? 

Eugene B.

unread,
Oct 22, 2011, 2:52:03 AM10/22/11
to rubyonra...@googlegroups.com
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.

Eugene B.

unread,
Oct 22, 2011, 3:56:45 AM10/22/11
to rubyonra...@googlegroups.com
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 :(.

Eugene B.

unread,
Oct 22, 2011, 4:05:03 AM10/22/11
to rubyonra...@googlegroups.com
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?

Colin Law

unread,
Oct 22, 2011, 5:35:15 AM10/22/11
to rubyonra...@googlegroups.com
On 22 October 2011 09:05, Eugene B. <li...@ruby-forum.com> 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

Reply all
Reply to author
Forward
0 new messages