[Ruby] Adding multiple new related ActiveRecord objects without an intermediate save step

Eric Hodel drbrain at segment7.net
Wed Nov 15 15:47:19 PST 2006


On Nov 15, 2006, at 3:37 PM, Randall Lucas wrote:

> 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.

Hold the Company in the user's session, add Contacts to it, then save  
it at the end.

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

-- 
Eric Hodel - drbrain at segment7.net - http://blog.segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com




More information about the Ruby mailing list