允许任意数量的整数 strong_params

Permit arbitrary number of integers with strong_params

我在想也许数组是可行的方法,但我不确定如何只允许整数数组。这是我的开头:

def put_params
  params.require(:project).permit(technologies: [])[:technologies]
end

我希望能够安全地接受任意数量的技术 ID。

只要将technologies参数作为数组传递,你只需要使用

def put_params
  params.require(:project).permit(:technologies)
end

此处的基本部分是传递参数的方式。您需要确保参数作为数组传递。您可以在 official documentation.

中阅读更多内容

The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:

GET /clients?ids[]=1&ids[]=2&ids[]=3

The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3" as "[" and "]" are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.

The value of params[:ids] will now be ["1", "2", "3"]. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.