How to capture the last DB insertion id?

Hi all,

I’ve got a model - Images - and when I insert a new image into that
db,table I would like to grab hold of the last insertion id of that
row/record and then process it further and save reworked version back
into the db.table again.

Example: a new image gets inserted as a db.table.row with ID =
12345678 (id = primary key)
The ID (12345678) is then retrieved and processed and inserted as
‘human_ref’ where it’s styled as 1234-5678 in the same db.table.row.

Any ideas of how to do this in Rails ? I guess I can use the
‘after_save’ callback inside the model - Image - to do the
processing, but how could I get hold of the last insertion id
easily ? IF AR is currently not able to present this last insertion
id easily, could a ‘AR.last_insertion_id’ method be created and added
to Ralls ?

Else I guess I would have to load the Image object again with a
select sql and then retrieve the id, but that seem expensive and a
bit complicated. I plan to insert big batches of images in this way,
ie: 100+ images in one go, so not having to execute a bundle of
queries repeatedly would be great from many different angles.

Any advice/guidance would be very much appreciated.

Kind regards,

Mats


“TextMate, coding with an incredible sense of joy and ease”

I am not sure if this is correct or not but i belive if you do
Image.save the id will be automatically set so you can just use Image.id
from then on. Though don’t quote me as i am still new to Rails also.

On 26 Feb 2006, at 01:53, Rob S. wrote:

I am not sure if this is correct or not but i belive if you do
Image.save the id will be automatically set so you can just use
Image.id from then on. Though don’t quote me as i am still new to
Rails also.

Thanks Rob!

Dang, I do love Ruby & Rails! This is all the code required to do
what I wanted to achieve. Sometimes it’s just too easy :wink:
Although I’m sure that someone else can improve on this code even
further.

class Image < ActiveRecord::Base

various validation routines and other bits

After Create method

after_create :create_img_ref

private

def create_img_ref
the_id = self.id.to_s
# split the 8 digit id into XXXX-XXXX format with a dash
self.img_ref = “#{the_id[0,4]}-#{the_id[4,8]}”
# then save it to the db record via an update
self.update
end

end

Hope this may help someone else someday.

Kind regards,

Mats


“TextMate, coding with an incredible sense of joy and ease”