Wednesday, April 20, 2011

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 http://stackoverflow.com/questions/648463/best-way-to-model-customer-address).

From stackoverflow
  • 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!

  • 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
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.