Assuming I have an ActionController::Parameters
object like
params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
I can call slice
on it or permit
to get/allow only certain parameters.
At first sight, they return the same thing
> params.slice(:a)
=> {"a"=>1}
> params.permit(:a)
[18:21:45.302147] Unpermitted parameters: b, c
=> {"a"=>1}
But if I call to_h
on it params.slice(:a).to_h
returns an empty hash, while params.permit(:a).to_h
returns an hash with key :a
. As far as I understood, this is the case, because :a
was not permitted.
What I wonder now is, what is the use case of slice
, if I could just use permit
?
One difference I could think of is permit
cuts nested hash if you don't explicitly specify the nested keys while slice
allows nested hash:
# params = { a: 'a', nested: { nested_1: 1, nested_2: 2 } }
params.permit(:a, :nested) # => { a: 'a' }
params.slice(:a, :nested) # => { a: 'a', { nested_1: 1, nested_2: 2 } }
Another difference is in Rails 4, permit
won't raise ActiveModel::ForbiddenAttributes
when calling in .update_attributes(...)
(answered here):
user.update_attributes(params.slice(:email)) # will raise ActiveModel::ForbiddenAttributes
user.update_attributes(params.permit(:email)) # wont raise error
slice
gives ability to slice a hash with selected keys.
where as .permit
returns a new ActionController::Parameters instance that includes only the given filters and sets the permitted attribute for the object to true. This is useful for limiting which attributes should be allowed for mass updating.
I would say slice is for everything dealing with Hash and permit is created using slice pattern but more in context of url params.
Hope it helps!
Also read this: http://apidock.com/rails/ActionController/Parameters/permit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With