Search code examples
ruby-on-rails-4parametersform-submitbelongs-to

In RoR, how do I avoid this "Unpermitted parameter" when submitting my form?


I’m using Rails 4.2.4. In my controller I have this

  def update
    @user = current_user
    if @user.save_with_address(user_params)
    …
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :dob, :address, :automatic_import)
    end

and in my model (based on my “users” table in which I have a “users.address_id” column), I have this

class User < ActiveRecord::Base
  belongs_to :address
  attr_accessor :address

but when I submit my form to my “update” method (shown above) with the following data

Parameters: {"utf8"=>"✓", "authenticity_token"=>”tjLutbCuZUmLImSRnoRUCtcG8O0u070YixqjnMm5hmAZhn94fFte4jpWgB4hoOstiP9vJTj/c081EJ8NYnbMvg==", "user"=>{"first_name"=>"D.", "last_name"=>”LastName”, "dob(2i)"=>"", "dob(3i)"=>"", "dob(1i)"=>"", "address"=>{"city"=>"golden", "state"=>"3547", "country"=>"0"}, "automatic_import"=>"0"}, "commit"=>"Save", "id"=>"1"}

I get a “Unpermitted parameter: address” message when my “user_params” function is called and my address object isn’t saved as part of my user object. What do I need to structure differently to avoid this?


Solution

  • Since address is a hash you have to specify all its individual fields.

    params.require(:user).permit(:first_name, :last_name, address: [:city, :state, :country])