不允许在Rails 4中嵌套参数

问题描述 投票:0回答:2

我一直在用这个撕掉头发。 我已经阅读了有关集成强大参数的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

来自客户端的JSON

{
    "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)

不允许的参数:章节。 我一直盯着这个看了好几个小时。 老实说,我不知道我在做什么错。 请告诉我它在那儿,我只是忘记了一些愚蠢的魔术参数,所以我可以继续前进。

ruby-on-rails ruby ruby-on-rails-4 nested-attributes strong-parameters
2个回答
2
投票

我相信您只需要在allowed_pa​​rams方法中更改为“ chapters”:

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

而不是“ chapters_attributes”


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"}}

如果您发布视图代码,我们可能可以相当迅速地找到问题所在。

© www.soinside.com 2019 - 2024. All rights reserved.