How to indicate the order to the delivery address and billing address in rails

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

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

This works very well, but now the form helpers do not work. Ie form_forwill only generate fields with type names address[zipcode], so I have to manually hack it to get billing_address[zipcode]and shipping_address[zipcode].

I assume that you can use unidirectional inheritance of the subclass table Addressin ShippingAddressand BillingAddress, but that seems a bit hacked to me (and contradicts some good answers to Best Modeling Customer ↔ Address ).

+3
source share
2 answers

I have two ideas for you: either or both of them can 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 the help of your form helpers, and I would be interested to know if this will work for you. Hope this helps!

+2
source

You need to specify the class name, since it is 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 connection:

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
+3
source

Source: https://habr.com/ru/post/1706053/


All Articles