views:

318

answers:

2

In my online store, each order is associated with a shipping address and a billing address (they can be the same, of course). This is my first attempt to model this:

Class Order
  belongs_to :billing_address, :class => "Address"
  belongs_to :shipping_address, :class => "Address"

This works pretty well, but now the form helpers don't work. I.e., form_for will only generate fields with names like address[zipcode], so I have to manually hack it to get billing_address[zipcode] and shipping_address[zipcode].

I guess I could use single table inheritance to subclass Address into ShippingAddress and BillingAddress, but this seems a bit hacky to me (and contradicts some good answers in http://stackoverflow.com/questions/648463/best-way-to-model-customer-address).

+1  A: 

Hello Horace, I have two ideas for you, either or both of which may do the trick:

Class Order
  belongs_to :billing_address, :class_name => "Address"
  belongs_to :shipping_address, :class_name => "Address"

Class Order
  belongs_to :address, :foreign_key => "billing_address_id"
  belongs_to :address, :foreign_key => "shipping_address_id"

Please give them a try with your form helpers and I'd be interested to know if it works out for you. Hope it helps!

Adam Alexander
+2  A: 

You need to specify the class name, since it's not BillingAddress or ShippingAddress.

class Order < ActiveRecord::Base
  # foreign key not required here because it will look for
  # association_name_id, e.g. billing_address_id, shipping_address_id
  belongs_to :billing_address, :class_name => "Address"
  belongs_to :shipping_address, :class_name => "Address"
end

To complete the association:

class Address < ActiveRecord::Base
  # foreign key required here because it will look for class_name_id, 
  # e.g. address_id
  has_many :billing_orders, :class_name => "Order", 
    :foreign_key => "billing_address_id" 
  has_many :shipping_orders, :class_name => "Order", 
    :foreign_key => "shipping_address_id"
end
Sarah Mei