Lesson Monday

Finally, it's time to delete an album. Let's add a delete button to our view for editing an album. Add the following code to the end of edit_album.erb:

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

  <button type="submit" class="btn btn-danger">Delete album</button>
</form>

This form is very similar to the code we added for a PUT request. The only difference is that we use a value of delete instead of patch. We also don't need to have any other form fields — our only goal here is to delete the album entirely.

Now let's add a route for deleting the album:

app.rb
delete('/albums/:id') do
  @album = Album.find(params[:id].to_i())
  @album.delete()
  @albums = Album.all
  erb(:albums)
end

Once again, it's very similar to our code for updating an album. The only difference is that we call delete instead of update.

We've successfully added all CRUD functionality for our record store. It's not much of a record store — not yet, anyway — but all the basic pieces are in place to build this out further.

Sample Form for Deleting


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

  <button type="submit" class="btn btn-danger">Delete album</button>
</form>

Sample Route for Deleting


app.rb
delete('/albums/:id') do
  @album = Album.find(params[:id].to_i())
  @album.delete()
  @albums = Album.all
  erb(:albums)
end

Lesson 23 of 37
Last updated August 7, 2022