2

I cannot get accepts_nested_attributes_for to work with strong parameters in Rails 4. This is the error

Processing by CityaddressesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Cx9nunLAsHkvo/Z8vKnWFnrub1LpmUgVNdePcQ9VDSQ=", "cityaddress"=>{"st_unit"=>"1", "st_num"=>"1", "st_prefix"=>"E", "name"=>"1", "st_type"=>"ST", "st_postalcode"=>"", "description"=>"", "cityaccount"=>{"name"=>"1", "description"=>"1"}}, "commit"=>"Create Cityaddress"}
  [1m[36mUser Load (0.0ms)[0m  [1mSELECT  `users`.* FROM `users`  WHERE `users`.`id` = 3 LIMIT 1[0m
Unpermitted parameters: cityaccount

This is the model:

class Cityaddress < ActiveRecord::Base
    has_many :cityaccounts
    has_many :license_plates
    accepts_nested_attributes_for :cityaccounts, allow_destroy: true

    def street_address
      return "#{st_unit} #{st_num} #{name} #{st_type} #{st_prefix}"
    end
    def address
      return "#{st_unit}#{st_prefix} #{name} #{st_type} #{st_num} "
    end
end

This is the controller:

  # GET /cityaddresses/new
  def new
    @cityaddress = Cityaddress.new
    @streets = Street.where("active=1").order("display_order")
    @cityaddress_accounts = @cityaddress.cityaccounts.build
  end

    def cityaddress_params
      params.require(:cityaddress).permit(:st_unit, :st_num, :st_prefix, :name, :st_type, :st_postalcode, :description, cityaccounts_attributes: [:name, :description, :id])
    end 

This is the view:

<%= f.fields_for @cityaddress_accounts do |ff| %>
   <div class="field">
     <%= ff.label :name %>
     <%= ff.text_field :name %><br>
   </div> 
   <div class="field">
     <%= ff.label :description %>
     <%= ff.text_field :description %><br>
   </div>  
<% end %>

I'm thinking it's something to do with the strong parameter syntax?

Cheers.

0

2 Answers 2

2

I think you have to change the view a bit.

Try changing this

<%= f.fields_for @cityaddress_accounts do |ff| %>

to

<%= f.fields_for :cityaccounts do |ff| %>
Sign up to request clarification or add additional context in comments.

2 Comments

That worked. Thanks. I'm wondering why, though. I didn't create a :cityaccounts variable...
It is the association name that you need to define as it is a nested attributes.
1

Seems all correct, but try in Controller do this:

  def new
    @cityaddress = Cityaddress.new
    @streets = Street.where("active=1").order("display_order")
    @cityaddress.cityaccounts.build
  end

1 Comment

Thanks. That didn't break anything and the @cityaddress_accounts variable was superfluous, I guess...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.