我一直用这个脱掉我的头发。我已经阅读了有关Rails 4集成强大参数的所有文档,现在所有内容都必须明确列入白名单。但它仍然不会经历!
这是我的设置
class Course < ActiveRecord::Base
has_many :chapters
accepts_nested_attributes_for :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :course
end
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
{
"course": {
"chapters": [{
"title": "qwerty",
"content": "foobar"
}],
"name": "Test course"
}
}
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)
未经许可的参数:章节。我一直盯着这几个小时都没有用。老实说,我不知道我做错了什么。请告诉我它就在那里我忘了一些愚蠢的神奇参数,所以我可以继续前进。
答案 0 :(得分:2)
我相信您只需要在allowed_params方法中更改为“章节”:
def permitted_params
params.require(:course).permit(:name, chapters: [:title, :content])
end
而不是“chapters_attributes”
答案 1 :(得分:1)
我认为问题不在控制器或模型中,而是在请求中发送的JSON中。
Processing by CoursesController#create as JSON
Parameters: {"course"=>{"chapters"=>[{"title"=>"qwerty", "content"=>"foobar"}], "name"=>"Test course"}}
应该是
Processing by CoursesController#create as JSON
Parameters: {"course"=>{"chapters_attributes"=>[{"title"=>"qwerty", "content"=>"foobar"}], "name"=>"Test course"}}
如果您发布视图代码,我们可能会很快找到问题。