ActionController::Parameters deprecation warning: Method size is deprecated and will be removed in Rails 5.1
Asked Answered
O

2

6

I recently came across this deprecation warning

DEPRECATION WARNING: Method size is deprecated and will be removed in Rails 5.1, as ActionController::Parameters no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited.

Params looked like this:

<ActionController::Parameters { "objects" => 
  <ActionController::Parameters {
    "0"=>{"priority"=>"24", "style"=>"three_pictures"}, 
    "1"=>{"priority"=>"24", "style"=>"three_pictures"}, 
    "2"=>{"priority"=>"24", "style"=>"three_pictures"}
} permitted: false> } permitted: false>

And I tried to find the size of objects like this: params[:objects].size

And then I tried the same thing with length and count, which results in the same warning. What would be the work around for this? .keys.length is something that works, but is this the correct way to do it or am I missing something here?

Optional answered 26/10, 2016 at 7:33 Comment(2)
you can convert params to hash using to_h and access those methods.Yokel
` Rails 5 ActionController::Parameters` now returns an Object instead of a Hash. To access the parameters in the object you can add to_h to the parameters:Yokel
S
7

As mentioned in the comments you have to convert params to Hash since in Rails 5 params no longer inherits from Hash. So .size, .length and .count won't work on params directly.

How to convert it to Hash (shorter code may be possible):

permitted_params = params.require(:your_model_name).permit(
  :product_inspirationals => [
    :priority, 
    :style
  ]
).to_h

puts permitted_params[:product_inspirationals].length

Don't know about your model structure so you have to adjust it to your needs.

Stingy answered 23/2, 2017 at 15:47 Comment(0)
I
-2

For hash, you can find the size by .size method.

The problem is not with the size method here, Problem is in the ActionController::Parameters which is not hash,


Look at the first line inside ActionController::Parameters

"0"=>{priority"=>"24", "style"=>"three_pictures"}

it should be following as " missing before priority

"0"=>{"priority"=>"24", "style"=>"three_pictures"}

After this .size method should be working

Isometrics answered 26/10, 2016 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.