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 Best way to model Customer <--> Address).
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
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