5

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?

Bruno E.
  • 934
  • 8
  • 15

2 Answers2

5

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
Community
  • 1
  • 1
Linh Dam
  • 1,494
  • 1
  • 15
  • 16
0

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

uday
  • 7,922
  • 4
  • 28
  • 50
  • `slice` also returns an instance of ActionController::Parameters again. And since that class was introduced for strong parameters, I wonder why the slice method which is an extension of Rails for the Hash class should be used. For pure hashes I agree that it makes sense to have it. – Bruno E. Sep 04 '16 at 18:33