Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong parameters and multidimensional arrays

I'm using Rails 3.2.6 with strong parameters gem.

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

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

Then, I have the permited_params method

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

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

Following the documentation, I need to specify :attr3 as 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

The question is: How can I use strong params with multidimensional arrays?

like image 225
Leantraxxx Avatar asked Aug 08 '14 19:08

Leantraxxx


People also ask

What are strong parameters?

Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.

Are multidimensional arrays useful?

They are very useful if you need them. For example, you could be dealing with 3D objects (x,y,z) coordinates or for mathematical research.


1 Answers

You can also do this in this way

   def permited_params
     hash = params.permit(:attr1, :attr2) 
     hash[:attr3] = params.require(:attr3) if params.has_key?(:attr3)
     hash
   end
like image 148
Paritosh Piplewar Avatar answered Sep 23 '22 14:09

Paritosh Piplewar