Skip to content Skip to sidebar Skip to footer

Save All User Entries From Html Text Built Off A Loop Using Ruby And Sinatra

I am creating a web page that displays a table. It also has four columns at the end of each record that are text fields where the user can enter data. When the user hits the submit

Solution 1:

By default when Sinatra (using Rack) parses the form data then if there are any duplicate keys then the last one is used and overwrites the others. However if you use a name that ends with [] then Sinatra instead creates an array containing all the entries with that name.

So in your case you need to change the names of the input elements:

<inputtype="text" name="event_description[]">

(and similarly for the others). Note the [] at the end of the name.

Now when you submit the form, params['event_description'] will be an array containing all the items submitted to the event_description input elements.

The Sinatra/Rack query parsing is actually more sophisticated than this, so you can go further with your form. In your loop you could do something like this:

<td><inputtype="text"name="events[][description]"></td><td><inputtype="text"name="events[][type]"><td><inputtype="text"name="events[][class]"><td><inputtype="text"name="events[][issue_expert]"></td>

Now when you submit the form and it is parsed, params['events'] will contain an array of hashes, each with keys description, type, class and issue_expert. You can then iterate over this array and process the data as appropriate. You may want to add a hidden id input with each hash to make sure each set of data is associated with the correct record (it might look something like <input type=hidden name="events[][id]" value="<% event.id %>">).

Post a Comment for "Save All User Entries From Html Text Built Off A Loop Using Ruby And Sinatra"