Forum: Ruby on Rails manually setting an auto-incremented primary key id

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C4359fdf1c79367e95e024f6ac9f0fc0?d=identicon&s=25 Jamie Forrest (Guest)
on 2009-02-12 22:22
(Received via mailing list)
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.)
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2009-02-13 00:36
(Received via mailing list)
On Feb 12, 2009, at 4:21 PM, Jamie Forrest 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 Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
C4359fdf1c79367e95e024f6ac9f0fc0?d=identicon&s=25 Jamie Forrest (Guest)
on 2009-02-13 04:08
(Received via mailing list)
On Feb 12, 6:35 pm, Rob Biedenharn <R...@AgileConsultingLLC.com>
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 Biedenharn          http://agileconsultingllc.com
> R...@AgileConsultingLLC.com

Thanks that worked like a charm.
This topic is locked and can not be replied to.