Ruby on rails 在订单上有单独的交货地址和帐单地址的最有效方式
我在Rails应用程序中有一个Ruby on rails 在订单上有单独的交货地址和帐单地址的最有效方式,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我在Rails应用程序中有一个地址模型和一个订单模型。订单有帐单地址和送货地址。我正试图找出用多态关联实现这一点的最有效方法(其他模型将来也会有地址),这是我提出的代码: 地址。rb: class Address < ActiveRecord::Base attr_accessible :line_1, :line_2, :city, :county, :postcode # Also has an 'address_type' attribute belongs_to :a
地址
模型和一个订单
模型。订单有帐单地址和送货地址。我正试图找出用多态关联实现这一点的最有效方法(其他模型将来也会有地址),这是我提出的代码:
地址。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
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\u address=
来更改地址外,这几乎可以正常工作,只是添加了另一个类型为“delivery”的地址。我也非常确定,一定有一种更优雅的方法来做这件事,我真的很感激任何建议。代码看起来很棒。我认为添加和更改地址之间的区别应该在您的控制器中处理,而不是在模型中,例如,在RESTful情况下,有用于创建
和更新
的方法,在这种情况下,您可以知道是替换值还是添加值
另请看,它会让您知道是否有更改。我想您的想法是相反的。地址应该有多个订单,订单应该属于两个不同的地址。所有这些方法都应该由这两个关联直接处理。我会完全删除地址类型。
has_one :delivery_address, as: :addressable,
conditions: "addresses.address_type = 'delivery'", class_name: "Address"
has_one :billing_address, as: :addressable,
conditions: "addresses.address_type = 'billing'", class_name: "Address"