rails: multiple request values with the same name
Let’s say you have a web app that takes input from the user. How about a phone book app for storing phone numbers. And let’s assume that each person in your phone book can have an unlimited number of phone numbers. In the interface you allow the user to fill in as many phone numbers as they’d like by dynamically creating more and more input=’text’ elements. When the user saves, the data that gets posted to the server looks something like:
/phonebook/save?number=5203842233&number=6029130923&number=9283125248
Basically there are multiple parameters that have the same name with different values. Now in Java to get the values of the numbers you would do something like…
request.getParameterList('number');
…to get an Array of Strings, each element containing one of the numbers (NOTE: my Java is rusty and this could be wrong). In rails there is no such getParameterList method. As I currently understand it, rails only sees the first number. So it thinks that number=5203842233 was the only value passed to the server, the other values are ignored. Looking at rail’s logs confirms this:
Parameters: {"controller"=>"phonebook", "action"=>"save", "number"=>"5203842233"}
So how do you get multiple values with the same name out of the request? You add ‘[]‘ to the parameter name (ie <input type=”text” name=”number[]“/>):
/phonebook/save?number[]=5203842233&number[]=6029130923&number[]=9283125248
Now looking at the log file:
Parameters: {"controller"=>"phonebook", "action"=>"save", "number"=>["5203842233","6029130923","9283125248"]}
When retrieving params[:number], you’ll end up with an Array of the numbers instead of just the first.




