Manually setting an auto-incremented primary key id


#1

I want to create a record with a manually-set custom ID, for instance:

Foo.create(:id => 8000, :name =>“bar”)

But when I try to do that, Rails ignores the id I pass and continues
to auto-increment the id in the table. So in other words the console
output is along the lines of:

Foo.find(:last)
=> #<Foo id: 52, name: “foo”>

Foo.create(:id => 8000, :name =>“bar”)
=> #<Foo id: 53, name: “bar”>

What’s the best way around this? (By the way, after I insert this
record with the custom ID, I do want it to revert back to auto-
incrementing the id.)


#2

On Feb 12, 2009, at 4:21 PM, Jamie F. wrote:

Foo.create(:id => 8000, :name =>“bar”)
=> #<Foo id: 53, name: “bar”>

What’s the best way around this? (By the way, after I insert this
record with the custom ID, I do want it to revert back to auto-
incrementing the id.)

Foo.create(:name => ‘bar’) do |foo|
foo.id = 8000
end

One caveat however that bit me last week doing something similar when
initializing some records in a new table. PostgreSQL has a sequence
created to support the auto-incrementing primary key (id) and I was
getting unique index errors when new (or editted!) records were being
saved and the sequence value was already a different record in the
table.

(My solution was to manually next values off each of the two sequences
until it would return a value that wasn’t already a key.)

-Rob

Rob B. http://agileconsultingllc.com
removed_email_address@domain.invalid


#3

On Feb 12, 6:35 pm, Rob B. removed_email_address@domain.invalid
wrote:

output is along the lines of:
Foo.create(:name => ‘bar’) do |foo|
(My solution was to manually next values off each of the two sequences
until it would return a value that wasn’t already a key.)

-Rob

Rob B. http://agileconsultingllc.com
removed_email_address@domain.invalid

Thanks that worked like a charm.