How does params[:id] not throw an exception even if we do not explicitly whitelist :id?

StackOverflow https://stackoverflow.com/questions/23410908

  •  13-07-2023
  •  | 
  •  

문제

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
도움이 되었습니까?

해결책

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.

다른 팁

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!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top