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:


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


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:


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

Another article/program that may be of interest is DeepMerge. This is a hash utility largely designed to make managing complex structures coming from the params object easier to cope with. Specifically, if you make a habit of stuffing params elements into session, and then want to update those elements in session with new data from params on a subsequent post, DeepMerge is for you.


Use this link to trackback from your own site.


Leave a response

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

    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 UTC

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

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

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