Sebastian
Sebastian

Reputation: 2279

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:

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.

Upvotes: 2

Views: 1630

Answers (2)

Adrien Coquio
Adrien Coquio

Reputation: 4930

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

Upvotes: 8

jaredonline
jaredonline

Reputation: 2902

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

Upvotes: 4

Related Questions