You can also use the methods included from ActiveRecord::Dirty on the
foreign key fields; in your case, you'd have an after_save callback
like this (on Person):

after_save :cleanup_addresses

def cleanup_addresses
  Address.destroy(shipping_address_id_was) if
shipping_address_id_changed? && shipping_address_id_was
  Address.destroy(billing_address_id_was) if
billing_address_id_changed? && billing_address_id_was
end

Some notes on this:

- if you don't have any callbacks or observers on Address, you can
simplify the .destroy calls to .delete, and save instantiating some
Address objects.
- if your UI allows users to swap the addresses (ie,
shipping_address_id is swapped with billing_address_id, without any
new DB records), you'll need to have a better check in
cleanup_addresses; the current code will end up deleting both
addresses in that case.

--Matt Jones

On Jul 24, 6:33 pm, Emma <gkilo...@gmail.com> 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 can inverse the association and use a has_one but then I have to put
> two foreign keys in the address table... and that could be a problem
> because there are other models that have addresses.
>
> Another option could be to model both associations as composed_of but
> then I have to put all of the address table columns on the people
> table, and repeat this on the other models that have addresses too.
>
> How can I solve this? Any suggestions?
> Thanks in advance.
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to