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 button at the bottom I want to save all the data in all the text fields and add it to my table. How can I save the data for all the text fields? Here is my code.
<h1>Testing Table</h1>
<form action="/table/" method="POST">
<table>
<thead>
<tr>
<% event_column.each do |header| %>
<th>
<%= header %>
</th>
<% end %>
</tr>
</thead>
<tbody>
<% events.each do |event| %>
<tr>
<% event = event.first(14) %>
<% event.each do |key, value| %>
<td>
<%= value %>
</td>
<% end %>
<td><input type="text" name="event_description"></td>
<td><input type="text" name="event_type">
<td><input type="text" name="event_class">
<td><input type="text" name="issue_expert"></td>
</tr>
<% end %>
</tbody>
</table>
<br/>
<input type="submit">
<% ActiveRecord::Base.clear_active_connections! %>
</form>
I understand my issue. Since I am using the same variable to write all of the user entered columns when I try displaying in my POST method
<td><%= params[:event_description] %></td>
It will only display the last value entered because it's being reused. Is there anyway that when I hit submit I can loop through all the html text fields and save all the data? I'm pretty stuck here and I've searched all around. I understand how to save the text entry for the last row but, I don't know how to save all the text entries. I'm new to sinatra so I must be doing something fundamentally wrong.
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:
(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 theevent_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:
Now when you submit the form and it is parsed,
params['events']
will contain an array of hashes, each with keysdescription
,type
,class
andissue_expert
. You can then iterate over this array and process the data as appropriate. You may want to add a hiddenid
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 %>">
).