0

我有一个要保存到数据库的 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

谢谢您的帮助。

4

1 回答 1

1

根据您的报告有多少属性,也许这样的事情会很实用

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
于 2013-09-05T18:42:32.023 回答