尝试使用嵌套表单为我的成员模型创建地址。
模型
class Member < ActiveRecord::Base
has_many :addresses, :as => :addressable, dependent: :destroy
accepts_nested_attributes_for :addresses
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
控制器
**new**
@member = Member.new
@member.addresses.build
**create**
@member = Member.new(member_params)
**update**
@member.update(member_params)
# Am I doing this right? Haven't gotten this far in the process without error.
**private**
# Never trust parameters from the scary internet, only allow the white list through.
def member_params
params.require(:member).permit(
:first_name,
:last_name,
:birthdate,
addresses_attributes: [:street1, :street2, :city, :state, :zip, :country, :id]
)
end
查看
= simple_form_for @member do |f|
= f.simple_fields_for :addresses do |address|
= address.input :street1
= address.input :street2
= address.input :city
= address.input :state
= address.input :zip
= address.input :country, :priority => [ "United States" ]
= f.submit "Save", class: "btn btn-success"
错误
ActiveModel::ForbiddenAttributesError
使用Pry
pry(#<MembersController>)> member_params
Unpermitted parameters: address
=> {}
pry(#<MembersController>)> params
=> {"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"44f8YqwLCuVKnKDC2uZUDodOjPtgi+EcJKPQh4IqwPA=",
"member"=>{"address"=>{"street1"=>"1234 Fake St.", "street2"=>"", "city"=>"Tacoma", "state"=>"WA", "zip"=>"999999", "country"=>"US"}},
"commit"=>"Save",
"action"=>"update",
"controller"=>"members",
"id"=>"1"}
希望有人可以帮忙! THX! 我不知道问题是什么......我非常确定我正确地接受了嵌套属性,对我出错的地方非常好奇!我是strong_parameters的新手,所以希望它简单明了......
更新 遵循建议并更改
= simple_fields_for :address do |address|
到
= simple_fields_for :addresses do |address|
我还更改了member_params以包含:address_attributes的id
...
addresses_attributes: [:street1, :street2, :city, :state, :zip, :country, :id]
...
我也尝试将:member_id添加到addresses_attributes但我仍然得到ForbiddenAttributesError
还有什么想到的吗? :)谢谢你们。
答案 0 :(得分:0)
你的参数中没有“addresses_attributes”,你只需要“地址”。如果您希望能够输入多个地址(您的数据模型建议),那么您需要更改为以下内容:
= simple_form_for @member do |f|
= f.simple_fields_for :addresses do |address|
= address.input :street1
...
正如Andrey在另一个答案中提到的那样,您还需要将:id
添加到address_attributes数组中的params列表中,如果您希望能够从表单中删除地址,则需要:_destroy
。