[Ruby] Adding multiple new related ActiveRecord objects without an intermediate save step
Randall Lucas
rlucas at tercent.com
Wed Nov 15 15:37:29 PST 2006
Does anyone here know of a design pattern or approach to the case of
adding many related objects to a main object prior to initially saving
(and therefore assigning an ID to) the main object in a Web (Rails) app?
Example:
Imagine a class:
Company < ActiveRecord::Base
:has_many => 'contacts' :through => 'company_contacts'
Now imagine a view where I use AJAX to add new contacts dynamically to
a form.
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.
The old-school answer to this is to make creating relations to Contacts
a stepwise process that happens only after the Company is created. But
that sucks for the user. Kluges I've used in the past include sticking
new objects into the session, and reassembling them after the fact, but
that usually means a lot of ad hoc, non-DRY code.
I've come across this problem so many times in so many contexts
(Company => Contacts, Question => Answers, etc.) that I can't imagine
that Rails folks don't have an approach to this. Yet, I can't find
anything in the Rails wiki or in my (2005 edition, admittedly) DT/DHH
Rails book.
Best,
Randall
--
Randall Lucas Tercent, Inc. DF93EAD1
More information about the Ruby
mailing list