Rails Params and Arrays 3

Posted by scientific on December 28, 2006


I still regularly bump up against a number of issues in Rails I don’t like but Rails is opinionated software so I’m learning to live with that. Either code around it or figure out the way Rails wants you to behave.

A lot of Rails is, of course, very well designed and thought through. One thing that has turned out to be pretty smart for me is the way it handles certain form fields data from a get/post request.
If you send a request to the Rails engine with data like “property[id]” it knows you’re talking about a table property with a field id. That’s not novel - I used similar syntax building web apps in 1995. Rails however also add this behavior:

"property[amenity_type_id][]" 

This says that the value associated with this key should be converted into an array. So if there are multiple such keys in the request object, they are serialized into an array which you can pull out in your controller code.. Example (get or post works):

http://myurl.com/path/to/action?property[amenity_type_id][]=1&property[amenity_type_id][]=3&property[amenity_type_id][]=9

In the controller you can access this by

values = params['property']['amenity_type_id']
values # => Array containing ['1','3','9']

Makes it easy to solve certain problems. But importantly you can also send “double values” as a single value, such as:

http://myurl.com/path/to/action?property[amenity_type_id][]=1,2&property[amenity_type_id][]=3&property[amenity_type_id][]=9

Which yields:

values # => Array containing ['1,2','3','9']

Issuing this statement:

values = values.join(',').split(',') # => yields ['1','2','3','9']

Handy for when you want a single checkbox or select list to return two values into the resulting array.. This also makes it easy to combine select lists, checkboxes and radio buttons all contributing data into a single backend location..

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. joost baaij Wed, 18 Jul 2007 13:00:49 EDT

    It’s the simple things that matter most. I had forgotten about this and it’s very handy sometimes! Great writeup, thanks.

  2. shaug Thu, 19 Jul 2007 17:38:02 EDT

    Don’t you mean values.join(’,').split(’,')?

  3. science Thu, 19 Jul 2007 18:41:55 EDT

    Shaug: Yes that’s exactly what I mean. Thanks for pointing that out. Corrected on main article now.

Comments