Trying to create a address for my member model with a nested form.
model
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
controller
**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
view
= 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"
Error
ActiveModel::ForbiddenAttributesError
Using 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"}
Hope someone can help! Thx! I don't see what the issue is... I'm pretty sure i'm accepting the nested attributes correctly, very curious to where I'm going wrong! I'm new to strong_parameters, so hopefully it's something simple...
UPDATE Followed suggestions and changed
= simple_fields_for :address do |address|
to
= simple_fields_for :addresses do |address|
and I also changed member_params to include :id for addresses_attributes
...
addresses_attributes: [:street1, :street2, :city, :state, :zip, :country, :id]
...
I also tried adding :member_id to addresses_attributes but I still get ForbiddenAttributesError
Anything else come to mind? :) thanks guys.
You don't have "addresses_attributes" in your params, you simply have "address". If you want the ability to input multiple addresses (which your data model suggests) then you need to change to something like this:
As Andrey mentions in another answer you also need to add
:id
to your list of params in the address_attributes array, and:_destroy
if you want to be able to remove addresses from the form as well.