Skip to content

Instantly share code, notes, and snippets.

@markjlorenz
Last active October 17, 2022 19:11
Show Gist options
  • Save markjlorenz/3724090 to your computer and use it in GitHub Desktop.
Save markjlorenz/3724090 to your computer and use it in GitHub Desktop.
Rails Query String to Params Cheat Sheet

#A hash of arrays: widget[]=first-widget&gadget[]=a-gadget&widget[]=another%20widget

Resulting Params:

{
    :widget => [ "first-widget",  "another widget"],
    :gadget => [ "a-gadget" ]
}

#An array of hashes: follows[][screen_name]=soodesune&follows[][presentation_id]=4&follows[][verify]=6ae9f180f13108&follows[][screen_name]=radiouman&follows[][presentation_id]=5&follows[][verify]=6ae9f180f13238

Resulting Params:

{
    follows:[
        {screen_name:"soodesune", presentation_id:"4", verify:"6ae9f180f13108"}, 
        {screen_name:"radiouman", presentation_id:"5", verify:"6ae9f180f13238"}
    ]
}
  • Note that with Express.js/Connect's bodyParser this would need to have the form follows[1][screen_name]=soodesune...

#A complex example: HTML:

<form action="forms/1802">
    <input name="form[form_drugs_attributes][0][_destroy]" type="checkbox" value="1">
    <input name="form[form_drugs_attributes][0][id]" type="hidden" value="200358">
    <input name="form[form_drugs_attributes][1][_destroy]" type="checkbox" value="1"> <!-- this one is checked -->
    <input name="form[form_drugs_attributes][1][id]" type="hidden" value="200359">
</form>

Sends: {"utf8"=>"✓", "authenticity_token"=>"B6...WQ=", "form"=>{"form_drugs_attributes"=>{"0"=>{"_destroy"=>"0", "id"=>"200358"}, "1"=>{"_destroy"=>"0", "id"=>"200359"}}}, "commit"=>"Submit", "id"=>"18028"}

The integer to indicate an array doesn't carry any significance outside of telling the params parser to put substrings with the same array number in to one object. It's not the #id in the database.

Or see the docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment