Olivier
Olivier

Reputation: 3400

accepts_nested_attributes_for whith json PUT (update)

I have seen many examples of using accepts_nested_attributes_for but only a few of them for json POST/PUT and none of them helped me :/

My application will be used to create forms.

So, a form has many form_rows and a form_row can have many choices (in case it is a select of radio). So, I have my form model like this :

class Form < ActiveRecord::Base
    attr_accessible :name
    has_many :form_rows
    accepts_nested_attributes_for :form_rows
end

and my controller looks like this :

def update
    @form = Form.find(params[:id])
    @form.update_attributes!(params[:form])
end

Here is the json I am trying to send

{
  "name": "form test 4",
  "form_rows_attributes": [
    {
      "domtype": "Input",
      "label": "Super row new"
    }
  ]
}

In my scenario, the form creation only takes a name, it is after that that the user add the form_rows.

When I do that, the name is correctly updated but the form_rows are not created at all. There is no error in my console, just the UPDATE for the form.

What am I doing wrong?

Upvotes: 2

Views: 1895

Answers (1)

patrickmcgraw
patrickmcgraw

Reputation: 2495

Your JSON needs one more level of nesting so the params[:form] call will actually find the params:

{ 
  "form": {
    "name": "form test 4",
    "form_rows_attributes": [
      {
        "domtype": "Input",
        "label": "Super row new"
      }
    ]
  } 
}

Upvotes: 6

Related Questions