如何在Ruby on Rails中将数组从视图传递到控制器 [英] How to pass an array from view to controller in Ruby on Rails
问题描述
在我看来,我需要添加(动态)文本输入,我需要在控制器中获取他们的值(一旦用户提交相应的表单)。
In my view I need to add (dynamically) text inputs and I need to get theirs values in the controller (once the user submit the corresponding form).
我的输入是:
<input type="text" name="airports_input_origin" class="airports_input_origin" id="airports_input_origin_0" size="40"/>
<input type="text" name="airports_input_origin" class="airports_input_origin" id="airports_input_origin_1" size="40"/>
等...
他们都有相同的'name'属性....所以我猜,如果我做
They all have the same 'name' attribute.... so I guessed that if I do
params[:airports_input_origin]
我会得到数组...但我错了...
I'd get the array ... but I was wrong...
如何获得这些值?
Thx!
推荐答案
您必须这样做:
<input type="text" name="airports_input_origin[0]" class="airports_input_origin" id="airports_input_origin_0" size="40"/>
<input type="text" name="airports_input_origin[1]" class="airports_input_origin" id="airports_input_origin_1" size="40"/>
如果您在名称中标记数字,Rails会知道它是一个数组。
Rails understand that it's an array if you tag numbers like that within the name.
所以你可以有一个JavaScript函数,迭代所有输入,并在每次添加/删除目的地时重置它们的数字。使用正则表达式来替换数字,或者甚至可能甚至硬编码的名称,并更改[x],如果这是所有必需的。
So you could have a JavaScript function that iterates over all the inputs and resets their numbers everytime a destination is added/deleted. Use regex to replace the numbers or you could probably even hard code the name and change the "[x]" if this is all that's required.
这篇关于如何在Ruby on Rails中将数组从视图传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!