【发布时间】:2013-09-05 15:03:43
【问题描述】:
我有一个要保存到数据库的 JSON 提要,在数据数组中,有一个属性是一个数组:
{
"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
感谢您的帮助。
【问题讨论】:
-
先保存报告怎么样,然后检查
if saved_reports.save块中的子数组并在那里创建它? -
如果父级只有一条记录,那会起作用,但父级也是一个数组,所以我要插入多个项目。我将如何最好地使用子数组来解决父级问题?我可以再次循环返回 saved_reports 吗?
标签: ruby-on-rails arrays json activerecord