Strong parameters and multidimensional arrays

I am using Rails 3.2.6 with strong parameters gem.

So, I have a controller with a typical update action:

# PUT /api/resources/:id
def update
  @resource.update_attributes! permited_params
  respond_with_json @resource, action: :show
end

Then I have a method permited_params

def permited_params
  params.permit(:attr1, :attr2, :attr3)
end

The problem is what :attr3is a multidimensional array like this:[[1, 2], [2, 5, 7]]

Following the documentation, I need to specify :attr3as an array. But...

params.permit(:attr1, :attr2, :attr3 => [])
#inspecting permited_params: {"attr1"=>"blah", "attr2"=>"blah"}

params.permit(:attr1, :attr2, :attr3 => [[]])
#inspecting permited_params: {"attr1"=>"blah", "attr2"=>"blah", "attr3" => []}

params.permit(:attr1, :attr2, :attr3 => [][])
#throw error

Question: How to use strong parameters with multidimensional arrays?

+4
source share
2 answers

You can also do it this way.

   def permited_params
     hash = params.permit(:attr1, :attr2) 
     hash[:attr3] = params.require(:attr3) if params.has_key?(:attr3)
     hash
   end
+3
source

, , .

, , , . .

String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch:: Http:: UploadedFile Rack:: Test:: UploadedFile.

scalar ::ActionController::Parameters::PERMITTED_SCALAR_TYPE

, , Array value.

, , , Array , ..

::ActionController::Parameters::PERMITTED_SCALAR_TYPE << Array

. . , . , , , , , -

def allow_array_in_strong_parameter
  old_scalar_types = ::ActionController::Parameters::PERMITTED_SCALAR_TYPES.dup
  ::ActionController::Parameters::PERMITTED_SCALAR_TYPES << Array
  params.permit(:attr1, :attr2, :attr3 => [])
  ::ActionController::Parameters::PERMITTED_SCALAR_TYPES = old_scalar_types
end
+2

All Articles