I finding this a bit mind bending and would like some ideas. My design goes likes this:
I need to define the associations between the builders-addresses and clients-addresses
My initial database design was like this:
Builders
--------------------
id
postal_address_id
...
Clients
--------------------
id
postal_address_id
billing_address_id
...
Addresses
-------------------
id
...
This seems logical to me, but I am having trouble translating this in rails associations.
I am thinking that addresses could define a belongs_to :addressable, polymorphic association. But how to I handle postal and billing addresses for the clients.
Any help will be much appreciated.
In a case like that I would use STI (Single table inheritance), I think it's the perfect case for that.
First, you have to add a field "type" in your address model.
Then you can define you classes like that :
class Client
has_one :billing_address, :as => :addressable
has_one :shipping_address, :as => :addressable
end
class Address < ActiveRecord:Base
belongs_to :addressable, :polymorphic => true
end
class BillingAddress < Address
end
class Shipping Address < Address
end
Read more about STI in the rails doc
You could just have an address_type column in the addressable table. Then you can scope the associations like so:
class Client
has_one :biling_address, :as => :addressable, :conditions => {:address_type => "billing"}
has_one :shipping_address, :as => :addressable, :conditions => {:address_type => "shipping"}
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With