【问题标题】:Parsing and saving a JSON sub-array in Rails在 Rails 中解析和保存 JSON 子数组
【发布时间】: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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2015-09-23
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2018-08-02
    相关资源
    最近更新 更多