How to pass an array from view to controller in Ruby on Rails

余生长醉 提交于 2019-12-11 03:39:18

问题


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).

My inputs are:

<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"/>

etc... etc...

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...

How can I get those values?

Thx!


回答1:


You'd have to do something like so:

<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 understand that it's an array if you tag numbers like that within the name.

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.



来源:https://stackoverflow.com/questions/6626636/how-to-pass-an-array-from-view-to-controller-in-ruby-on-rails

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