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: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