[Rails] [AR] save method and associations

Xavier Priour xavier at priour.com
Sat Jan 15 14:24:58 GMT 2005


(previous post attempt died on me -damn webmail- without apparently being sent.
Please ignore if it WAS sent and this ends up as a double post)


An ActiveRecord::Base object is only persisted in the DB when you call its "save" 

method. BUT adding an object to an association persists the associated object 

immediately. And saving an object does NOT save its associated objects. I find
this a 

bit confusing.

Moreover, my app does the following: fetch an object from the DB, and then
update not 

this object, but its associated objects. Which causes me to have to manually go 

through all the objects and save them where necessary.

I'd rather make all my modifications, associations, and so on, and then call save 

once, on the main object, knowing that ActiveRecord will at this moment issue
exactly 

the relevant DB calls to update all objects.

I've looked around ActiveRecords code, and here's the proposal:
- flag active records when their fields or associations are modified
- create association objects in memory only
- when save is called, crawl down the associated in-memory objects:
  + send flagged objects to DB
  + update their id field if necesary
  + then unflag them

DB save order (for IDs), cycle and delete detection would probably be the main 

issues.

What do you think? I remember someone wrote about adding associated objects to
unsaved ones, this could be related.

If it's OK, I'm ready to start working on this. Should I fill a TRAC ticket or
something?

Xavier Priour

-------------------------------------------------
This mail sent through IMP: http://horde.org/imp/


More information about the Rails mailing list