Search code examples
ruby-on-railsruby-on-rails-4parametersmass-assignment

Rails - Mass-Assignment ForbiddenAttributesError for nested attribute


I'm having an issue with mass assignment for nested attributes. I'm having a hash in params that represents an object that results from a form_for form.

I tried to authorize the params like this but I get the following error...

ActiveModel::ForbiddenAttributesError

for

params.require(:country).permit(:language, :flag_path)
@country.update(params[:country])

Here is the params array :

{"utf8"=>"✓",
 "authenticity_token"=>"xxxxxxx",
 "country"=>{"language"=>"xxxx",
 "flag_path"=>"xxxxx"},
 "commit"=>"Update",
 "country_id"=>"xxxx"}

Thanks for your help.

EDIT : I know it is possible to user permit! but if I understand correctly, this authorize all parameters for the ressource and I'd like to permit only some of it.


Solution

  • There are two problems in your code:

    1st: Consider if below is your permit param method in your controller :

    def country_param
      params.require(:country).permit(:language, :flag_path)
    end
    

    then your update action should be like this:

    @country.update(country_param)
    

    not

    @country.update(params[:country])
    

    2nd: Why you have country_id in your update action. It should be id instead. It's not big one both will work. But with country_id You will not reach to proper edit action.

    Anyway according to your params your action should be look like:

    def update
      @country = Country.find(params[:country_id])
      @country.update(country_param)
    end
    
    private
    
      def country_param
        params.require(:country).permit(:language, :flag_path)
      end