Lesson Monday

We've added logic for showing a list of albums and adding new albums. We're ready to add information for showing a specific album's detail information.

First, we'll add code to app.rb:

app.rb
...

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

This route allows us to pass a parameter into a dynamic URL. If we pass in localhost:4567/albums/12, we can then find the specific album with the id of 12. Whenever we want to pass a parameter into the URL, we'll use a symbol. We could call this :id or :name or something else. However, clear and concise naming should always be prioritized.

Next we use our find method to get a specific album and then save that album in the instance variable @album. Note that we need to convert the parameter to an integer because it comes to us in the form of a string. @album is now available for use in our view.

Next, let's add a file called album.erb. We'll keep it very simple:

album.erb
<h4>Album Name: <%= @album.name %></h4>

<p><a href="/albums/<%= @album.id %>/edit">Edit album</a></p>
<a href="/albums">Return to album list</a>

Our album detail page doesn't have much on it. However, a real world application would have images, summaries, and other details that we wouldn't show on our main page. We also add a link to an album edit view (which we haven't created yet).

Back in albums.erb, let's also make our list of albums clickable:

albums.erb
...
  <% @albums.each do |album| %>
    <li><a href="/albums/<%= album.id %>"><%= album.name %></a></li>
  <% end %>
...

In the href attribute, we use an expression tag to pass in the value of an individual album's id: <%= album.id %>. This way, each album has its own unique link.

Next, we'll add functionality to update individual albums.

Routing for READING an Individual Album


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

Creating a link to a specific album:

albums.erb
<% @albums.each do |album| %>
  <li><a href="/albums/<%= album.id %>"><%= album.name %></a></li>
<% end %>

Lesson 21 of 37
Last updated August 7, 2022