DEV Community

loading...

Getting arrays in the params hash for sinatra

Jason Crockett
Christian backend Dev who groans when javascript stuff needs to be implemented by him.
・2 min read

God or an Angel litterly told me the answer to this one when i was walking out of the bathroom. I am christian coder, and God helps me code.

short answer:

do something like this:
<select id="users-select" form="search-form" name="users[]" multiple>

the key is to have "[]" in the name

The story behind it:

so i was writing a search engine for note taking app and i was noticing that in my templates that options that were selected in a multiple choice input only reflected the last option in the url. my url looked like this:

http://localhost:4567/reports?clients=5e399c1d181b8942a418c10d&clients=5e52c3f5181b894bcc285cfa

so only the option with the value 5e52c3f5181b894bcc285cfa.

i dispaired slightly having found a (what i thought was a) project crashing bug. Oh no! i thought, im going to have to do double work learning ember or angular or something, specifying the model on front end and the back end stack! and my javascript is a bit lacking! this would push back the completion deadline by months!

so i decided to try the sinatra param gem which is here:

Sinatra Param Github

no luck. the types of the param values probably were coerced but params would still only return the last value on the url for that param name.

so i decided to solve it the only way someone who depends on open source should respond to a problem like this. with prayer and project contribution. so i opened an issue here..

My Sinatra Repo issue

and cloned sinatra ready for a pull request after my hack. If God was willing. when im solo, i leave tests until last. but this is a team effort so testing comes first. so i searched in the test folder using rubymines "search in path" command for mentions of params and i came across a behaviour spec at line 575 of this file

Sinatra/test/routing_test.rb

so i noted it in the sinatra issue, shelved it for the night and gamed to 4am because i woke up at 2pm becuase of a persistant migrain and im off sick and working on a project.

the next day after my post wakeup routine i came out of the bathroom and i heard an angel speak to me.

he said something like use brackets in the name attributes of my form inputs. Of Coarse! So i went and tried it out to my success and reported it on the sinatra issue and found out that i had a reply. Github user dentarg found a stack exchange question which i hadnt:

The reply

The Stack Exchange Question

They both did not mention how you got the names in the url like that but my angel friend did.

Thanks God and his messenger!

Discussion (0)