How to get the id field before a save


I have a situation where I am parsing an XML file, and in the process
I create several related groups of objects. I am currently creating
and saving each one in sequence, but this is causing a huge number of
COMMIT’s to be called in the SQL. What I would like to do, is store
every object of the same type that is created in an array, and then
save them all at once, wrapped in a transaction call, so that there is
only one COMMIT called on every table. The problem I’m having is that
there is an order of dependency among the objects, so Object2 depends
on Object1’s id as its foreign key. Without the call to save, Object1
does not have an id assigned to it, so the eventual save on object 2
fails. Is there any way to get this value (auto-incrementing in the
DB) without all the extra overhead?



How would you write SQL to do that? The only way I can think you would
do it is to use a stored procedure, generate your own primary keys
(hoping they don’t clash!!!), and do something like an
IDENTITY_INSERT. Otherwise you will have to insert the row to get its
primary key.

If all you need is a single transaction, then maybe you can use
Object.transaction. But I thought I heard a rumour that that was being
depreciated. Is that true?

On 30 Mar 2007, at 16:03, Simon wrote:

fails. Is there any way to get this value (auto-incrementing in the
DB) without all the extra overhead?

An object doesn’t have to be saved for you to relate other objects to

Note that the point when objects are saved depends on which way round
you associate them. So if you assign an object to a has_one
relationship in an existing object, that associated object will be
automatically saved. But if you assign a new object to a belongs_to
relationship, it won’t be automatically saved.

See pp 356-357 of Agile Web D. With Rails v2.

Hope that helps.

Andy S.