[英]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. 这很好用,但现在表单助手不起作用。 Ie,
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]
. 即,
form_for
只会生成名称类似address[zipcode]
字段,所以我必须手动破解它才能获得billing_address[zipcode]
和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 ). 我想我可以使用单表继承将
Address
子类化为ShippingAddress
和BillingAddress
,但这对我来说似乎有些苛刻(并且以最佳方式对客户< - >地址建模的一些好答案进行了反驳)。
You need to specify the class name, since it's not BillingAddress or ShippingAddress. 您需要指定类名,因为它不是BillingAddress或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
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!
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.