name
and id
properties. The other part is understanding how the input is passed into and accessible in Sinatra through the params hash. For example, let's say I have a form for pirates:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form action='/pirates' method="POST"> | |
<h2>Pirates:</h2> | |
<br> | |
<ul> | |
<li> | |
<label for="pirate0-name">Pirate name:</label> | |
<input type="text" name="pirates[0][name]" id="pirate0-name"> | |
<br /> | |
<label for="pirate0-weight">Pirate weight(lb):</label> | |
<input type="text" name="pirates[0][weight]" id="pirate0-weight"> | |
<br /> | |
<label for="pirate0-age">Pirate age:</label> | |
<input type="text" name="pirates[0][age]" id="pirate0-age"> | |
<br /> | |
<label for="pirate0-weapon">Pirate's favorite weapon:</label> | |
<input type="text" name="pirates[0][weapon]" id="pirate0-weapon"> | |
</li> | |
<!-- Some more pirates --> | |
</ul> | |
<br> | |
<input type="submit" value="Submit" /> | |
</form> |
It would look like this:
How would I access the data sent? I add to my app a route
/pirates
that will handle a POST request, access the params hash and create some new pirates, and then return a new page:
post '/pirates' do
@new_pirates = params[:pirates].map { |pirate_num, attributes|
Pirate.create(attributes) if attributes[:name] != ""
}.compact
erb :"success.html"
end
Simply put, this takes
params[:pirates]
, which is a hash containing numbers (:0, :1, :2, etc.) as keys and pirate attribute hashes as values, and then creates new Pirate objects (which must be defined elsewhere) for any set of defined attributes, and finally renders a page which displays the newly input information (which is stored in @new_pirates
), which can also be accessed later (if items are saved to a database).We spent the afternoon working on two labs where we created Sinatra apps with forms and displayed the output, optionally writing tests and persisting to a database. I had enough time to write tests for the first lab (I actually developed it entirely with tests first), and persist both to a database.
Skills developed: Linked lists, Sinatra with forms, RSpec testing in Sinatra
No comments:
Post a Comment