[Ruby] Adding multiple new related ActiveRecord objects

Randall Lucas rlucas at tercent.com
Thu Nov 16 14:08:32 PST 2006


> > This is fine for editing an existing Company.  But if I follow the
> > scaffolding pattern (new vs. create) for making a new Company, I won't
> > yet have a @company.id to supply for my new Contacts when I try
> > AJAXically to add them.
> 
> Hold the Company in the user's session, add Contacts to it, then save  
> it at the end.

Eric, thanks -- I have used this method in the past with other
frameworks and home-brewed systems, but I was hoping that Rails would
have a more formalized process for this.

For example, if you just add it to the session, then you risk stomping
on it if the person works in two browser windows to add two different
Company objects.  So, you add a per-action token and store your new
objects in a hash keyed to the token, etc.  And then you realize that
incomplete actions or back-and-forth browser action gums up the hash
with lots of never-to-be-saved objects for long-lived sessions, so then
you create a timestamp and expire out the incomplete objects, etc. 

All of which is doable, but involves a lot of choices and repetition --
am I overlooking a more Rails-y way to do this?

> Or, just save the Company straight up and make deletion super-easy.

Yes, except you then lose (or have to hack around) the Rails validation
patterns for e.g.  Company's required fields, because you save the
Company early to get its id.

Best,

Randall

-- 
Randall Lucas       Tercent, Inc.       DF93EAD1


More information about the Ruby mailing list