0

I have a JSON feed that I'm saving to the database, and within the array of data, there is a property that's an array:

{
   "reports": [
      {
         "name1":"val1",
         "name2":"val2",
         "sub": [
            {"x":9,"y":-8,"z":134},
            {"x":10,"y":-7,"z":136}
         ]
       }
    ]
}

The sub-array values will be saved into its own table so my question is: how can I easily insert the parent records, get the identity of the newly created record, and then save the sub-array records?

This is what I have so far, but as you could guess, the id of the sub-array values is 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

Thanks for the help.

2
  • What about just saving the report first, then check for the sub array in a if saved_reports.save block and create it there? Commented Sep 5, 2013 at 18:14
  • That would work if the parent was only one record, but the parent is also an array so I'm inserting multiple items. How would I best resolve the parent with the subarrays? Would I just loop back through saved_reports again? Commented Sep 5, 2013 at 18:30

1 Answer 1

1

Depending on how many attributes your Report has, maybe something like this would be practical

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.