Forum: Ruby on Rails Knowing id before a call to 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.
Martin G. (Guest)
on 2006-05-17 21:41
(Received via mailing list)
Hiall,

Is it possible to find out the value for the id field of any record
before it was actually saved, i.e. if new_record? returns true?

To motivate this:
I have a parent model which should not exists alone but needs a few
other (child) models to be initialized whenever a new record of parent
is instantiated. Needless to say, the child models need the id of the
parent model as foreign key. I know I could do that in a call to a
public parent model method after I saved it, but I want this to be
done in the initialize method. Yes, I have setup my has_one and
has_many relations.

Any ideas?

cheers
Martin
Michael T. (Guest)
on 2006-05-17 21:45
(Received via mailing list)
The id is assigned by the database not the model, so no.  Use an
observer like after_update to do the work.

Michael
Martin G. (Guest)
on 2006-05-17 22:25
(Received via mailing list)
Hi Michael,

Thx for the tip! I could have thought of the fact the db assigns the
pk value if following the rails conventions. However, what would it be
like if the pk wasn't set to auto_increment ? This is just out of
curiosity actually :) I'm a nice guy and follow the rails conventions
so your solution is perfectly acceptable for me, although I might go
with a simple callback method not a full blown observer :)

Thx!
Martin
Michael T. (Guest)
on 2006-05-17 22:37
(Received via mailing list)
If not following convention, and you're assigning the pk, well you're
assigning the pk.  In that case you have it ahead of time and you can
create the children first.  The only gotcha is if you have foreign key
constraints in your database, that may prevent you from doing so.

I would also not use an observer in that case.

Michael
Martin G. (Guest)
on 2006-05-17 22:56
(Received via mailing list)
Hehe sillly me! Now that you say it, once again it's so obvious :) It
seems I am a little bit slow thinking today :-) Thx anyway for your
fast an precise response!

cheers
Martin
This topic is locked and can not be replied to.