[Rails] Questions on Managing Complex Objects
James Britt
james.britt at gmail.com
Mon Nov 22 07:57:55 GMT 2004
I'm looking at Rails, tryng out an application that is quite similar to the
Friends/Phone relational tutorial on rubyonrails.org. I'm puzled by the
automatic mangemnt of complex objects (e.g., Foo objects contain an array of
Bar objects, with Foo data going in one table, and Bar data going into another,
linked by a foreign key).
What the tutorial doesn't seem to show, and I can't figure out, is how to get
Rails to manage the creation/persisting of complex objects without my explcitly
adding the code to save the dependant objects .
For example, given the Person/Phones example, each person may have zero or more
phone numbers.
http://rubyonrails.org/show/TutorialBasicRelational
When I create a person object, I would want to set all the personal data, and
add some phone numbers, ideally in one step:
person = Person.new( :name => "Foo bar", :city => "Gotham",
:phones => [ '123-3456', '111-3333' ] )
At some point in my code I would save the person object:
person.save
and be done, trusting that the person details go into the People table, and
phone numbers go into the Phones table.
The tutorial shows the creation or editing of a person, with the optional
addition of phone numbers, but the code suggests that the code for creating and
saving the phone data (as part of a Person object) must be manually added; that
Rails does not automagically know that the @phones array should also be stored
when the parent person object is saved, and know how to store it.
The code here
http://rubyonrails.org/show/TutorialRelationalForms
manages phones by refering to the person object, but simply uses the person as
a sort of phone factory, creating independant objects that are linked via the
database, but not asociated as objects per se. In other words, you do not see
what I would expect if there was no database involved:
@person.phones < Phone.new( value )
or even
@person.phones < @person.build_to_phones( value )
Likewise for all the CRUD operations. From playing around, I find that if I
delete a Person object, the related phone numbers remain in the Phones table.
Have I misunderstood something? Maybe skipped a step someplace? Does Rails
know how do do this sort of dependant mapping and persistence?
Thanks,
James
More information about the Rails
mailing list