How to pass an array from view to controller in Ru

2019-07-09 00:39发布

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条回答
欢心
2楼-- · 2019-07-09 01:32

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.

查看更多
登录 后发表回答