Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give an order a shipping address and a billing address in rails

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).

like image 953
Tom Lehman Avatar asked Dec 06 '25 15:12

Tom Lehman


1 Answers

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
like image 199
Sarah Mei Avatar answered Dec 08 '25 05:12

Sarah Mei



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!