Save all user entries from html text built off a loop using ruby and sinatra

本小妞迷上赌 提交于 2019-12-01 10:43:18

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:

<input type="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><input type="text" name="events[][description]"></td>
<td><input type="text" name="events[][type]">
<td><input type="text" name="events[][class]">
<td><input type="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 %>">).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!