Question

In rails 4.x, strong_parameters require parameters to be explicitly permitted. Yet, in the following example, I do NOT get a ForbiddenAttributesError - why does :id not throw when in the show action even though it is not explicitly permitted?

def FooController
  ...
  def show
    @foo = Foo.find(params[:id]) # why no exception here?
  end

  private
    def foo_params
      params.require(:foo).permit(:name, :address) # note: No :id here
    end 
end
Was it helpful?

Solution

See: http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

"With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted."

Doing a find is completely valid, and is, in fact, shown in the example in the documentation linked to, above.

OTHER TIPS

Strong parameters are used only for assignment of attributes. You can freely search and perform other operations with any param, just not mass assignment.

You can see more in-depth explanation and examples in Rails Guides

For Rails, params[:id] outside from default params.

  • Query string: www.example.com/foo/123?bar=1&baz=2

  • Request path: www.example.com/foo/123 where 123 is params[:id]

  • Paramerts: bar=1&baz=2 this can be permitted

If you pass 123 to parameters then you need permitted :id.

There is no need of explicitly permitting the :id unless you want to.Rails will do it implicitly.If want to check whether the :id is whitelisted or not,you can do puts params[:foo] after it is created or you can just see the log.you will see something like this

{id=>some_id, "name"=>"some_name", "adddress"=>"some_address"}

So,defining a Foo object like this

@foo = Foo.find(params[:id])

will not throw an exception.

Hope it helped!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top