Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Building Web Apps with Sinatra Updating Data Submitting the Edit Form Via PUT Request

Amir Tamim
Amir Tamim
8,597 Points

No clue how to accept a PUT request.

Could show me how to make the following accept a PUT request?

views/edit.erb
<p>Please enter your name below.</p>

<form method= "post" action= "/signatures/<%= @index %>">
   <input type="hidden" name="_method" value="put">
  <input type="text" name="signature" value="<%= @signature %>">
  <input type="submit">
</form>
guestbook.rb
require "sinatra"

def load_signature(index)
  # Code omitted for brevity
end

# Updates the line at the given index and re-saves the file.
def update_signature(index, signature)
  lines = File.readlines("signatures.txt")
  index = index.to_i
  lines[index] = signature
  File.open("signatures.txt", "w") do |file|
    file.puts lines
  end
end

get "/:index/edit" do
  # Code omitted for brevity
end

get "/signatures/new" do


end
put "/:title" do 
  save_content(params["title"],params["content"])
  redirect URI.escape ("/#{params["title"]}")
end 
Amir Tamim
Amir Tamim
8,597 Points

FULL QUESTION: Now we need a Sinatra route to accept the PUT request with the form parameters. Create a put route that will match any path with a format like /signatures/0, /signatures/1, /signatures/5, etc. The numeric part of the path should be captured in a URL parameter named index.

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

OK, so take a look at your other routes - they always start with the verb (get, post...) and then are followed by the actual path that we want, in this case, an example path would be '/signatures/1'. The number needs to be dynamic, so we want to keep it in a parameter. The parameter is to be named index according to the challenge. We name these parameters using the : symbol, so a parameter called name would look like this: :name.

Knowing all this, the route you want to build should look like this:

put "/signatures/:index" do

end

Make sure you understand this before proceeding and please rewatch the video as many times as you need to get a full grasp. There's nothing wrong with watching these videos more than once, trust me :)