Forum: Ruby on Rails how to get the id field before a save

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.
7dd10e685d07b10fa95a4b8c33387922?d=identicon&s=25 Simon (Guest)
on 2007-03-30 17:04
(Received via mailing list)
Hi,

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?

Thanks,

Simon
72ee7b478a235f646c3495f03ebbe676?d=identicon&s=25 Andrew Stewart (Guest)
on 2007-03-30 17:20
(Received via mailing list)
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
it.

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 Development With Rails v2.

Hope that helps.

Regards,
Andy Stewart
A45f650cce5746dd89aafb3176b47b02?d=identicon&s=25 DyingToLearn (Guest)
on 2007-03-31 18:07
(Received via mailing list)
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?
This topic is locked and can not be replied to.