Ruby on rails 在Rails中解析和保存JSON子数组
我有一个保存到数据库的JSON提要,在数据数组中,有一个属性是数组:Ruby on rails 在Rails中解析和保存JSON子数组,ruby-on-rails,arrays,json,activerecord,Ruby On Rails,Arrays,Json,Activerecord,我有一个保存到数据库的JSON提要,在数据数组中,有一个属性是数组: { "reports": [ { "name1":"val1", "name2":"val2", "sub": [ {"x":9,"y":-8,"z":134}, {"x":10,"y":-7,"z":136} ] } ] } 子数组值将保存到它自己的表中,因此我的问
{
"reports": [
{
"name1":"val1",
"name2":"val2",
"sub": [
{"x":9,"y":-8,"z":134},
{"x":10,"y":-7,"z":136}
]
}
]
}
子数组值将保存到它自己的表中,因此我的问题是:如何轻松插入父记录,获取新创建记录的标识,然后保存子数组记录
这是我到目前为止所知道的,但正如您所猜测的,子数组值的id是nil
rpts = metrics['reports']
saved_reports = Report.create rpts do |r|
if (r.sub != nil) then
SubReport.create r.sub do |a|
# How do I get the ID of the parent record?
a.report_id = r.id
end
end
end
感谢您的帮助。根据您的报告有多少属性,类似的内容可能会很实用
rpts = metrics['reports']
rpts.each do |r|
report = Report.new name1: r.name1, name2: r.name2
if report.save && !r.sub.nil?
# save sub report here
end
end
如果先保存报告,然后检查
中的子数组(如果保存了报告)。保存块并在那里创建它怎么样?如果父项只有一条记录,但父项也是一个数组,则可以这样做,因此我要插入多个项。如何最好地解析具有子阵列的父级?我是否可以再次循环查看保存的报告?