如何在rails中订购送货地址和帐单邮寄地址

时间:2009-04-07 16:00:48

标签: ruby-on-rails e-commerce modeling

在我的在线商店中,每个订单都与送货地址和帐单地址相关联(当然,它们可以相同)。这是我第一次尝试对此进行建模:

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

这很好用,但现在表单助手不起作用。即,form_for只会生成名称为address[zipcode]的字段,因此我必须手动破解它才能获得billing_address[zipcode]shipping_address[zipcode]

我想我可以使用单表继承将Address子类化为ShippingAddressBillingAddress,但这对我来说似乎有些苛刻(并且与{{3}中的一些好答案相矛盾})。

2 个答案:

答案 0 :(得分:3)

您需要指定类名,因为它不是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

完成关联:

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

答案 1 :(得分:2)

我有两个想法,其中一个或两个都可以解决问题:

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"

请与你的表格助手一起试试,我很想知道它是否适合你。希望它有所帮助!