使用Rails的ActiveRecord在以下JSON代码段中将两个子地址记录存储在父货件记录下的最佳方法是什么?
显然,存储子记录的标准方法是配置普通的has_many
- belongs_to
关系,但在这种情况下,父记录“有两个”子记录,我认为不合适,加上has_many
- belongs_to
关系不允许将一个记录定位到另一个记录上的方式相同(即:shipment.to_address
不会“不行”
非常感谢任何帮助。
由于
{
"id": "shp_vN9h7XLn",
"to_address": {
"id": "adr_zMlCRtmt",
"name": "Dr. Joe Bloggs",
"company": null,
"street1": "323 Some Dr",
"street2": null,
"city": "Example City",
"state": "XX",
"zip": "00000",
"country": "XX",
"phone": "0000000000",
"email": "example@example.com",
"created_at": "2013-04-22T05:39:56Z",
"updated_at": "2013-04-22T05:39:56Z"
},
"from_address": {
"id": "adr_VgoLT6Ex",
"name": "Some Rep",
"company": "Example Co.",
"street1": "43 Example St",
"street2": null,
"city": "Example City",
"state": "XX",
"zip": "00000",
"country": "XX",
"phone": "0000000000",
"email": "support@example.com",
"created_at": "2013-04-22T05:39:57Z",
"updated_at": "2013-04-22T05:39:57Z"
},
"tracking_code": null,
"refund_status": null,
"created_at": "2013-04-22T05:40:57Z",
"updated_at": "2013-04-22T05:40:57Z"
}
答案 0 :(得分:0)
IMO,您的2个地址不同,一个适用于from_address
,另一个适用于to_address
from_adress
to_adress
from_address
和to_address
都只是地址。因此,您可以使用Rails的STI(单表继承)功能来解决此问题。我想您熟悉STI,所以只需提供最终代码
class Shipment < ActiveRecord::Base
has_one :from_address, class_name: Address::FromAddress.name
has_one :to_address, class_name: Address::ToAddress.name
# Blah blah
end
要成为明确的定义,您甚至可以毫无顾虑地为一批货物存储多个to_adress
。
有关详细信息,请阅读Rails's Guide # Single Table Inheritance