Strong parameters and multidimensional arrays

…衆ロ難τιáo~ 提交于 2019-12-04 06:21:24

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

I was seeing this type of question many times so i though to dig into the code and find the reason and make it work.

It turns around that whatever written in documentation is correct. This is from strong parameter documentation.

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

This scalar values are inside stored in ::ActionController::Parameters::PERMITTED_SCALAR_TYPE

If you see its value, you will find that it doesn't accept Array as value .

To make this work, all you need to do to add Array into whitelist, i.e if you do

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

it will work. But this is bad solution. I'm not the strong_parameter contributor so i am not aware of security risks. So, to solve this problem all you have to do is to include method in your controller something like this

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!