【问题标题】:Unpermitted parameter with nested attributes具有嵌套属性的不允许参数
【发布时间】:2015-09-02 17:34:22
【问题描述】:

我正在尝试使用accepts_nested_attributes_for,但是当我尝试在地址模型中创建或更新字段时,我得到了unpermitted parameters: address

我在两个模型之间有一个关系,客户端的地址如下

class Client < ActiveRecord::Base
    has_one :address
    accepts_nested_attributes_for :address
    ...

class Address < ActiveRecord::Base
    belongs_to :client

强参数根据这个http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html设置 如下

  def client_params
        params.require(:client).permit(:name, :tel, :email, :website, :photo,
            address_attributes: [:id, :line1, :line2, 
            :town, :country, :zip_code])
  end

控制器中的更新动作使用client_params

def update
    @client = Client.find(params[:id])
    if @client.update(client_params)
    ...

表单使用form_forfield_for

form_for :client, url: path, method: mymethod, html: {multipart: true, role:'form'} do |f|
    = f.text_field :name
    ...
    = f.fields_for :address do |a|
        = a.text_field :line1, label: 'First line'
        = a.text_field :line2, label: 'Second line'
        = a.text_field :town
        = a.text_field :country
        = a.text_field :zip_code

客户端字段工作正常。但是,如果我尝试更新其中一个地址字段,则地址未更新,unpermitted parameter: address 将被记录。

这是来自此类请求的参数

Parameters: { 
 "utf8"=>"✓",
 "authenticity_token"=>"Yx+ualZcCUZTriCIiCfF1SrFVUGdOnFgWApiYqKAMXU=",
 "client"=> {
    "name"=>"Alice",
    "email"=>"",
    "tel"=>"",
    "website"=>"",
    "address"=> {
        "line1"=>"Casa 1",
        "line2"=>"",
        "town"=>"",
        "country"=>"",
        "zip_code"=>""}},
   "commit"=>"Save Details",
   "id"=>"16"}

【问题讨论】:

    标签: ruby-on-rails-4 nested-attributes strong-parameters


    【解决方案1】:

    我之前的回答大多是无关紧要的。这就是我认为的问题所在,参数中的嵌套属性要求必须引用模型名称的复数

    address_attributes: 必须是复数 addresses_attributes:

    我认为这就是问题所在。

      def client_params
            params.require(:client).permit(:name, :tel, :email, :website, :photo,
                addresses_attributes: [:id, :line1, :line2, 
                :town, :country, :zip_code])
      end
    

    请告诉我进展如何。

    【讨论】:

    • 感谢您的回复@Val,您的示例代码比我的更清晰,但我看不出结构与我的结构有何不同。你能指出我需要改变什么吗?
    • 你是对的。这很尴尬。对不起。真的。让我更深入地了解您发布的其余代码。如果我看到了什么,我会更新我的答案并让你知道。
    • @cdog 你的表格有些奇怪,我一开始没听懂。我在答案中添加了一个部分并更新了表单代码 sn-p。告诉我进展如何。
    • @cdog 你解决了吗?我一直在想它,我想我发现了一些很容易错过的东西。我更新了我的答案。这是一个简单的测试。
    • 我想我已经通过将嵌套属性的语法更改为 :address => [...] 解决了强参数的问题。 permit 现在返回我期望的哈希值。
    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 2013-04-01
    • 2017-06-03
    • 2016-02-06
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多