Rails: Need help defining association for address table

强颜欢笑 提交于 2020-01-01 17:26:00

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/6353317/rails-need-help-defining-association-for-address-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!