On Saturday 25 July 2009, Emma wrote: > I'm having trouble with this model: > > class Person < AR::B > belongs_to :shipping_address, :class_name => 'Address' > belongs_to :billing_address, :class_name => 'Address' > end > > class Address < AR::B > end > > The problem is that I want Address to be a Value Object (as in DDD), > and if I do this: > p = Person.create :shipping_address => Address.new(...) > > and later I change the address: > p.shipping_address = Address.new(...) > p.save > > the first address object doesn't get deleted from the DB. It becomes > an orphan.
I'd try to handle a case like this in a callback. ActiveRecord automatically generates methods like #shipping_address_id_changed?, but that does only half the job in this particular case, because assigning an unsaved object (such as Address.new) to a belongs_to association does not change the existing foreign key immediately. class Person < AR::B belongs_to :shipping_address, :class_name => 'Address' belongs_to :billing_address, :class_name => 'Address' protected def before_save if shipping_address_id_changed? || shipping_address && (shipping_address_id != shipping_address.id) Address.delete(shipping_address_id_was) if shipping_address_id_was end # same for billing_address; better extract the common code end end The code probably won't work as is, but it might get you started. Also, have a look at the :autosave option for belongs_to. HTH, Michael -- Michael Schuerig mailto:mich...@schuerig.de http://www.schuerig.de/michael/ --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---