为对象轨创建嵌套构建

时间:2016-05-18 10:39:06

标签: ruby-on-rails ruby-on-rails-4 build nested-attributes

我的JSON API如下所示,

{ "schedule_id": "1",
  "latitude" : 17.4327,
  "longitude" : 78.4302,
  "device_id": "123test",
  "audit_compliances":[
    {
      "value": "Yes",
      "score": 10,
      "remarks": "some remarks",
      "private_remarks": "some remarks",
      "check_point_id": 1,
    "audit_compliance_documents":[{
      "score": 10,
      "remarks": "some remarks",
     }]
   }]

我有一个关系,我希望立即保存所有这些记录,所以我想用细节初始化对象,并构建内部对象。开始像这样构建,但我如何构建文档的内部构建。

submission = Submission.new(audit_schedule_id: params[:schedule_id],
  latitude: params[:latitude], longitude: params[:longitude], 
  device_id: params[:device_id])
params[:audit_compliances].each do |audit_compliance|
  submission.audit_compliances.build(
    value: audit_compliance[:value],
    score: audit_compliance[:score],
    remarks: audit_compliance[:remarks],
    private_remarks: audit_compliance[:private_remarks],
    check_point_id: audit_compliance[:check_point_id])
end

1 个答案:

答案 0 :(得分:0)

直接将你的json param传递给提交参数 像这样

 params[:submission] = json_params;

 Submission.create(params[:submission]);

如果您的映射正确,它将创建两个........