有没有办法发送类似下面的二维数组参数
{ 'bar' => { 'foo' => [[10, 100], [20, 200], [30, 300]] } }
使用6 number_field_tag
?
我试过了:
<%= number_field_tag "bar[foo][][]" %>
但它没有工作
是'bar' => { 'foo' => nil }
答案 0 :(得分:1)
我无法想到从6个盒子中构建2D数组的方法,但你可以做的是构建2个1D数组,然后将它们组合到你所在的任何页面的另一端。访问。例如:
<%= number_field_tag "bar[foo][]" %>
<%= number_field_tag "bar[foo][]" %>
<%= number_field_tag "bar[foo][]" %>
<%= number_field_tag "bar[foo2][]" %>
<%= number_field_tag "bar[foo2][]" %>
<%= number_field_tag "bar[foo2][]" %>
构建一个如下所示的参数列表:"bar"=>{"foo"=>["10", "10", "10"], "foo2"=>["9", "9", "9"]}
然后在接收端,将两者结合起来很简单:
array = params[:bar][:foo].zip(params[:bar][:foo2])
生成以下数组:
[["10", "9"], ["10", "9"], ["10", "9"]]
据我所知,没有办法在params散列中设置2D数组,但我可能错了。希望这能满足您的需求:)
答案 1 :(得分:0)
我遇到了同样的问题,并通过以下解决方案解决了该问题,该解决方案适合将任何尺寸的数组发布到Ruby on Rails:
在Ruby on Rails中创建函数: 另一种方法是保存之前,遍历参数,获取值并将其推入新的空数组,然后使用此新数组设置params的array字段,这也可以完成工作。
(我已发表评论作为解释)
@array_1 = params[:params][:array_1] # suppose your params name is
# 'params' and you want to get
# the attribute in this json
# params 'array_1' which is an
# array, but Ruby rails will
# transform it to an object if
# not doing algorithms as below.
if @array_1
array_1 = []
@array_1.each do |a|
@a = a[1] # here could be any number you want to get the
# data you want to put in the array, puts the a
# first to check it out
if @child_array_1
@child_array_1 = a[1]['child_array_1'] # suppose the name
# is 'child_array_1'
# in your json object
# for the first child
# array
child_array_1 = []
@child_array_1.each do |child|
child_array_1.push(child[1]) # number 1 can be changed as
# you want as above array_1
end
a[1]['child_array_1'] = child_array_1
end
array_1.push(a[1])
end
@array_1 = array_1
@params.array_1 = @array_1 # suppose the first array attribute in
# your json object is 'array_1'
end