[Rails] Re: Questions on Managing Complex Objects

James Britt james.britt at gmail.com
Mon Nov 22 23:55:48 GMT 2004


Michael Koziarski wrote:
>>Have I misunderstood something?  Maybe skipped a step someplace? Does Rails
>>know how do do this sort of dependant mapping and persistence?
> 
> 
> You can use @person.phones.create to achieve what you're looking for
> 
> "# collection.create(attributes = {}) - returns a new object of the
> collection type that has been instantiated with attributes and linked
> to this object through a foreign key and that has already been saved
> (if it passed the validation)."
> 
> or build if you don't want it saved immediately

OK, this looks promising, and I see now that phone data is
automatically saved when the owning person object is saved, though if 
the person object is new, it apparently must be first explicitly saved 
before any new associated phone objects can be added (which, assuming 
the underlying mechanics, makes sense, as they need to get a row ID from 
the related object).

But, continuing with the same tutorial example, it appears that calling
  'destroy' on a person instance deletes the data for that person
from the 'people' table, but leaves the related phone data intact.

The code from the tutorial shows this:

      Person.find(@params["id"]).destroy

which successfully removes data from 'people', but has no effect on any 
phone records.

How can I tell Rails that when a person object with a given id is
destroyed, that all related phone data should be destroyed as well?  The 
way it is presented in the tutorial, the 'phones' table will continue to 
collect orphaned data.

Do I need to code up 'before_destroy' someplace, and loop over owned 
collections and explicitly call 'destroy' on each item?


Thanks for the help,

James



More information about the Rails mailing list