[英]Saving nested JSON object to database
可以说我有一个模特。
乘客属于航班。 航班属于旅行
class Trip < ActiveRecord::Base
has_many :flights, :dependent => :destroy, :order => "order_num ASC"
end
class Flight < ActiveRecord::Base
belongs_to :trip, touch: true
has_many :passengers, :dependent => :destroy
end
class Passenger < ActiveRecord::Base
belongs_to :flight, touch: true
end
我将其发送回rails应用程序。 (当用户调用保存时)。
*最高层是旅程
{
name: 'Hello Trip',
date: '2013-08-12',
flights: [
{
id: 1
depart_airport: 'RDU',
arrive_airport: 'RDU',
passengers: [
{
user_id: 1,
request: true
}
]
},
{
depart_airport: 'RDU',
arrive_airport: 'RDU',
passengers: [
{
user_id: 1,
request: true
},
{
user_id: 2
request:true
}
]
}
]
}
现在,我将保存的json放入并手动循环浏览航班,以查看是否有ID。 如果有我正在更新。 如果没有,我正在创建一个新的。 然后添加乘客。
我想知道Rails是否采用一种自动格式可以为我做所有保存。 我知道当您提交嵌套表单时,它会创建类似的模式,并添加_destroy属性,并且如果刚刚创建,则id是时间戳。 JSON保存会与此类似吗?
谢谢你的帮助!
是的,您应该可以在此处使用accepts_nested_attributes_for
。
您需要在模型上启用accepts_nested_attributes_for
,例如
class Trip < ActiveRecord::Base
has_many :flights, :dependent => :destroy, :order => "order_num ASC"
accepts_nested_attributes_for :flights, :allow_destroy => true
attr_accessible :flights_attributes
end
您还需要确保JSON响应使用Rails可以识别的密钥。 您可以修改JSON响应,也可以执行以下操作:
response = JSON.parse(json_string)
response[:flights_attributes] = response.delete(:flights)
# ...
那你就可以做
Trip.create(response)
您将要确保一切都按预期创建/更新。 有关accepts_nested_attributes_for
更多信息,请参见文档: http : //apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for 。
我认为accepts_nested_attributes_for
很方便,但是请注意,有些人认为应该弃用它(例如,在这里: http : //blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat -activerecord-models / ,请参见此处以获取响应: https : //stackoverflow.com/a/17639029/1614607 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.