Knowing id before a call to save



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?



The id is assigned by the database not the model, so no. Use an
observer like after_update to do the work.



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 :slight_smile: 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 :slight_smile:



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.



Hehe sillly me! Now that you say it, once again it’s so obvious :slight_smile: It
seems I am a little bit slow thinking today :slight_smile: Thx anyway for your
fast an precise response!