Question

I've been ripping my hair off with this one. I have read all the doc about Rails 4 integrating strong params and that now everything has to be explicitly whitelisted. But it still won't go through!!!

Here is my setup

Models

class Course < ActiveRecord::Base
  has_many :chapters
  accepts_nested_attributes_for :chapters
end

class Chapter < ActiveRecord::Base
  belongs_to :course
end

Controller

class CoursesController < ApplicationController
  respond_to :json

  def create
    @course = Course.create permitted_params
    respond_with @course
  end

  private

  def permitted_params
    params.require(:course).permit(:name, chapters_attributes: [:title, :content])
  end
end

JSON from client

{
    "course": {
        "chapters": [{
            "title": "qwerty",
            "content": "foobar"
        }],
        "name": "Test course"
    }
}

Server log

Started POST "/json/courses" for 10.0.2.2 at 2014-02-24 15:29:44 +0000
Processing by CoursesController#create as JSON
  Parameters: {"course"=>{"chapters"=>[{"title"=>"qwerty", "content"=>"foobar"}], "name"=>"Test course"}}
Unpermitted parameters: chapters
Completed 201 Created in 96ms (Views: 52.1ms | ActiveRecord: 4.1ms)

Unpermitted params: chapters. I've been staring at this for hours with no avail. I honestly don't know what I'm doing wrong. Please tell me its right there and I just forgot some stupid magical param so I can move on.

Was it helpful?

Solution

I believe the issue is not in the controller or model, but in the JSON sent in the request.

Processing by CoursesController#create as JSON
Parameters: {"course"=>{"chapters"=>[{"title"=>"qwerty", "content"=>"foobar"}], "name"=>"Test course"}}

should instead be

Processing by CoursesController#create as JSON
Parameters: {"course"=>{"chapters_attributes"=>[{"title"=>"qwerty", "content"=>"foobar"}], "name"=>"Test course"}}

If you post your view code we can probably track down the issue fairly quickly.

OTHER TIPS

I believe you just need to change to 'chapters' in your permitted_params method :

def permitted_params
    params.require(:course).permit(:name, chapters: [:title, :content])
end

instead of "chapters_attributes"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top