我的 Rails 应用程序中有一个Address
模型和一个Order
模型。一个订单有一个帐单地址和一个送货地址。我试图找出通过多态关联来实现这一点的最有效方法(其他模型将来也会有地址),这是我想出的代码:
地址.rb:
class Address < ActiveRecord::Base
attr_accessible :line_1, :line_2, :city, :county, :postcode
# Also has an 'address_type' attribute
belongs_to :addressable, polymorphic: true
end
订单.rb:
class Order < ActiveRecord::Base
has_many :addresses, as: :addressable
def delivery_address
addresses.where(address_type: 'delivery').first
end
def delivery_address=(address)
address.address_type = 'delivery'
addresses << address
end
def billing_address
addresses.where(address_type: 'billing').first
end
def billing_address=(address)
address.address_type = 'billing'
addresses << address
end
end
添加地址:
Order.first.address = Address.new(line_1: 'My House', city: 'Cityville, county: 'Hazzard')
除了尝试通过再次调用来更改地址order.delivery_address=
只是添加另一个“交付”类型的地址之外,这几乎可以工作。我也很确定必须有一种更优雅的方式来做这件事,我非常感谢任何建议。