Last Updated: February 25, 2016
·
19.79K
· hopsoft

Pass arrays & objects via querystring the Rack/Rails way

Rails has some great patterns for passing complex objects via querystring.

Arrays

numbers[]=1&numbers[]=2&numbers[]=3

# rails
params[:numbers]

# returns
[1, 2, 3]

Objects

user[id]=1&user[name]=Nathan

# rails
params[:user]

# returns
{
  id: 1, 
  name: "Nathan"
}

Complex Objects

users[][id]=1&users[][name]=Nathan&users[][id]=2&users[][name]=Emma

# rails
params[:users]

# returns
{ 
  users: [
    {
      id: 1, 
      name: "Nathan"
    }, 
    {
      id: 2, 
      name: "Emma"
    }
  ]
}

Experiment

You can try all this out yourself from a Rails console.

rails c

data = { numbers: [1,2,3] }
CGI.unescape data.to_query