Using Path Components as Input

Most web applications use URL paths to influence the content of a particular page. Look at this Amazon url:

Wow that's a very long URL! But for now, let's ignore everything after the ?:

Amazon responds with a page showing a second-generation Echo:

If you study the URL for a bit, you may notice the part that says B06XCM9LJ4 which just happens to be the "ASIN", or Amazon identification number, for the second-generation Echo.

We can test our theory by using this exact same URL but swapping in a different ASIN in that spot:

We now get a page for giftcards!

Dynamic Path Segments

We have discovered that the second part of an Amazon URL path acts as a dynamic segment that influences the HTML response.

When we do something like this in config/routes.rb:

resources :books

we also have a URL that supports a dynamic segment in the second part of the URL path:


Here, the 9 is the second path component and it is allowed to be dynamic: it can be anything. Rails will capture this value in the params hash like this:

Parameters: { "id" => "9" }

This means that our code can retrieve the actual value in the dynamic segment like this:


Here's an example of how we would apply this to our application:

<%# This is app/views/books/show.html.erb %>

<% book = Book.find_by(id: params["id"]) %>

Our variable book now refers to the row in the database that was indicated in the URL. In other words, our show.html.erb will automatically reflect the book identified by the URL.