Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Need help defining association for address table

I finding this a bit mind bending and would like some ideas. My design goes likes this:

  • There is builders table, each builder can have a postal address
  • There is a clients table, each client can have a postal address and a billing address
  • There is an addresses table

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.

like image 244
Sebastian Avatar asked Nov 18 '25 14:11

Sebastian


2 Answers

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

like image 182
Adrien Coquio Avatar answered Nov 20 '25 03:11

Adrien Coquio


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
like image 37
jaredonline Avatar answered Nov 20 '25 03:11

jaredonline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!