Lesson Monday

We're ready to add update functionality to our application. First we need a route for our edit form:

app.rb
...

get('/albums/:id/edit') do
  @album = Album.find(params[:id].to_i())
  erb(:edit_album)
end

This route does the exact same thing as our '/albums/:id' route — the only difference is that they render different embedded Ruby files.

Next, let's add a view for our edit form:

views/edit_album.erb
<h1>Update <%= @album.name() %></h1>

<form action="/albums/<%= @album.id() %>" method="post">
  <input name="_method" type="hidden" value="patch">

  <label for="name">Rename album</label>
  <input id="name" name="name" type="text">

  <button type="submit" class="btn btn-success">Update</button>
</form>

<p><a href="/albums">Return to album list</a></p>

Note that we're using the POST method. Sinatra doesn't have support for PUT (also known as PATCH) and DELETE methods so we have to fake a PUT request. We'll do this by adding the following line: <input name="_method" type="hidden" value="patch">. This specifies that we're using the PATCH method and that the field should be hidden. The field is hidden because we don't want users to alter it or deal with it.

Now let's add code to app.rb so we can actually update an album:

app.rb
patch('/albums/:id') do
  if params[:name] != ""
    @album = Album.find(params[:id].to_i())
    @album.update(params[:name])
  end
  @albums = Album.all
  erb(:albums)
end

It's pretty straightforward. So long as the user input is not empty, we find the album and update its name. Then, we save all the albums in a variable, and then render albums.erb.

Sample Form for Editing


views/edit_album.erb
<h1>Update <%= @album.name() %></h1>

<form action="/albums/<%= @album.id() %>" method="post">
  <input name="_method" type="hidden" value="patch">

  <label for="name">Rename album</label>
  <input id="name" name="name" type="text">

  <button type="submit" class="btn btn-success">Update</button>
</form>

Sample Code for Update Route


app.rb
patch('/albums/:id') do
  if params[:name] != ""
    @album = Album.find(params[:id].to_i())
    @album.update(params[:name])
  end
  @albums = Album.all
  erb(:albums)
end

Lesson 22 of 37
Last updated August 7, 2022