【发布时间】: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_for 和field_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