强大的参数和多维数组 [英] Strong parameters and multidimensional arrays

查看:85
本文介绍了强大的参数和多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Rails 3.2.6 strong参数 gem一起使用.

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

然后,我有permited_params方法

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

问题在于:attr3是一个多维数组,如下所示:[[1, 2], [2, 5, 7]]

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

在文档之后,我需要将:attr3指定为数组.但是...

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

问题是:如何在多维数组中使用强参数?

推荐答案

您也可以通过这种方式

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

这篇关于强大的参数和多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆