Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the attribute when receiving an ActiveModel::ForbiddenAttributesError

When using strong_params and getting an ActiveModel::ForbiddenAttributesError exception, how do I find out which attribute is forbidden? I've just switched from attr_accessible and the debug message was normally pretty good there but not when switching to strong params.

I receive this error:

ActiveModel::ForbiddenAttributesError in SnippetsController#create

This is a nested model.

def snip_params
  params.require(:snippet).permit(:content, :approved, :user_id, :book_id)
end

In the parent I've used

has_nested_attributes :snippets

The create

def create
  @snippet = @book.snippets.create(snip_params)
  @snippet.user = current_user
  if @snippet.save
    redirect_to @book
    flash[:success] = "Snippet submitted and awaiting approval."
  else
    flash[:base] = "Someone else has submitted a snippet, please try again later"
    redirect_to @book
  end
end

Params Contents:

{"utf8"=>"✓",
 "authenticity_token"=>"bTRSwFRIhN3l3DkkWPtLzpoQHYD+CezmJQLw8Oz5+3g=",
 "snippet"=>{"content"=>"<p>AAAAAAAAAAAAA</p>\r\n"},
 "commit"=>"Create Snippet",
 "book_id"=>"1"}
like image 855
Shaun Frost Duke Jackson Avatar asked Nov 29 '13 13:11

Shaun Frost Duke Jackson


1 Answers

All attributes are forbidden initially. This exception is only raised when you don't permit any attributes. If you permit some and not others, then the log output tells you which parameters were not permitted.

 params = ActionController::Parameters.new(name: 'Bob', age: 24) 
 #params are usually set automatically in the controller
 Person.new(params)

The above will raise the exception

 Person.new(params.permit(:name))

This will create a person with name 'Bob', the log output will also contain:

Unpermitted parameters: age
like image 151
Slicedpan Avatar answered Oct 28 '22 22:10

Slicedpan