具有嵌套属性的未允许参数

时间:2015-09-02 17:34:22

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

我正在尝试使用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"}

1 个答案:

答案 0 :(得分:0)

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

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

请告诉我它是怎么回事。