Ruby on rails 在Rails中创建深度嵌套对象
我构建了一个小API,当发布一个JSON对象时,它会创建具有代表性的模型记录。数据如下所示:Ruby on rails 在Rails中创建深度嵌套对象,ruby-on-rails,activerecord,orm,Ruby On Rails,Activerecord,Orm,我构建了一个小API,当发布一个JSON对象时,它会创建具有代表性的模型记录。数据如下所示: { "customer": { "email": "michael@myemail.com", "first_name": "Michael T. Smith", "last_name": "", "shipping_address_1": "", "telephone": "5551211212", "source": "Purchase" },
{
"customer": {
"email": "michael@myemail.com",
"first_name": "Michael T. Smith",
"last_name": "",
"shipping_address_1": "",
"telephone": "5551211212",
"source": "Purchase"
},
"order": {
"system_order_id": "1070",
"shipping_address_1": "",
"billing_address_1": "123 Your Street",
"shipping": "0",
"tax": "0",
"total": "299",
"invoice_date": 1321157461,
"status": "PROCESSING",
"additional_specs": "This is my info!",
"line_items": [
{
"quantity": "1",
"price": "239",
"product": "Thing A",
"comments": "comments"
"specification": {
"width": "12",
"length": "12",
},
},
{
"quantity": "1",
"price": "239",
"product": "Thing A",
"comments": "comments"
"specification": {
"width": "12",
"length": "12",
},
},
]
}
}
问题是如何创建嵌套对象。我的模型设置如下:
class Order < ActiveRecord::Base
has_many :line_items
belongs_to :customer
accepts_nested_attributes_for :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
has_many :specifications
end
class Specification < ActiveRecord::Base
belongs_to :LineItem
end
有更好的方法吗?目前我遇到了以下错误:ActiveRecord::ApicController中的AssociationTypeMismatch#采购#请求行项目(#70310607516240)应为,得到哈希(#70310854628220)
谢谢 为关联定义了一个新的setter方法:附加有\u属性的原始名称
在您的例子中,在您的订单
模型上有一个line\u items\u attributes=
方法,您需要使用该方法来利用嵌套属性功能。在构建模型之前交换密钥这样简单的操作可能会起作用,例如:
@data[:order][:line_items_attributes] = @data[:order].delete(:line_items)
@order = @customer.orders.build(@data[:order])
@order.save
您可以使用accepts\u嵌套的\u属性\u,如下所示:
(在我的例子中,产品有许多生产路线,而生产路线属于产品)
model/product.rb
has_many :production_itineraries, dependent: :delete_all
accepts_nested_attributes_for :production_itineraries, allow_destroy: true
型号/生产路线图.rb
belongs_to :product
要实例化:
products = Product.new
products.production_itineraries.build(other_production_itineraries_fields)
执行此操作后,保存产品后,生产日程对象将自动保存,并带有相应的产品id字段
products = Product.new
products.production_itineraries.build(other_production_itineraries_fields)