# Rails Router: Dynamic Segments and Query Strings

*Published on June 22, 2024*

Tags: Router

---


> This post is part of my&nbsp;[handbook on the Rails Router](/tag/router).

Consider this route:

```ruby
get "profile" => "pages#profile"
```

As you can guess, when the Rails application receives a request on the &nbsp;`/profile`&nbsp;page, it will direct that request to the&nbsp;`profile`&nbsp;method on the&nbsp;`PagesController`&nbsp;class.

At the same time, Rails provides the controller and action name in a hash called&nbsp;`params`&nbsp;in the controller.

```ruby
# controllers/pages_controller.rb

class PagesController < ApplicationController
  def profile
    puts params # {"controller"=>"pages", "action"=>"profile"}
  end
end
```

The main use of the&nbsp;`params`&nbsp;hash is to access the user-submitted information, such as query string parameters in the URL or the form data when the user submits the form.

### Dynamic Segments

So far, we've seen static URLs, such as&nbsp;`/posts`,&nbsp;`/about`, and&nbsp;`/profile`. However, often your application URLs may contain dynamic content, such as&nbsp;`/posts/20`,&nbsp;`/users/2`, or&nbsp;`/articles/learn-ruby`, where the numbers 20, 2, and the text&nbsp;`learn-ruby`&nbsp;can vary depending on what resource the user is trying to access.

If your routes have this kind of dynamic content, i.e. parts of the URL that can vary, the Rails routing system lets you define them in the route, and make them available in the&nbsp;`params`&nbsp;hash in the controller.

You can make a route dynamic by providing segment keys in the URL pattern. Consider the following route with two dynamic segments,&nbsp;`:section_name`&nbsp;and&nbsp;`:slug`.

```ruby
get 'section/:section_name/article/:slug', to: 'articles#show'
```

Now consider what will happen when you visit the URL _**localhost:3000/section/rails/article/activerecord**_.

Rails will extract the values of dynamic segments&nbsp;`:section_name`&nbsp;and&nbsp;`:slug`, that is,&nbsp;`rails`&nbsp;and&nbsp;`activerecord`&nbsp;respectively; and make them available in the&nbsp;`params`&nbsp;hash:

```ruby
# controllers/articles_controller.rb

class ArticlesController < ApplicationController
  def show
    puts params
  end
end

# Output

params = {
  section_name: "rails",
  slug: "activerecord
  # ... other information such as controller and action name
}
```

Now in your controllers, you can read these dynamic segments to generate and dispatch appropriate response, i.e. an article on ActiveRecord under the Rails section.

To generate the URL, you have to provide the values for the segment keys. For example, given this route:

```ruby
get "songs(/:genre)", to: "songs#index", as: "songs"
```

Calling&nbsp;`songs_path(genre: "pop")`&nbsp;in your application will generate the path `"/songs/pop"`.

### Optional Dynamic Segments

You can also make your dynamic segments optional by wrapping them in parenthesis. For example,

```ruby
get 'songs(/:genre)', to: 'songs#index' 
```

This route will match both&nbsp;`/songs/happy`&nbsp;and&nbsp;`/songs`&nbsp;and will be routed to the `index`&nbsp;action on the&nbsp;`SongsController`&nbsp;class.

If you want to provide default values for the dynamic segments, you can do so by providing the&nbsp;`:defaults`&nbsp;option.

```ruby
get "songs(/:genre)", to: "songs#index", defaults: { genre: "rock" }
```

When the user visits&nbsp;`songs/pop`, the&nbsp;`params[:genre]`&nbsp;will be&nbsp;`pop`. However, if they visit only&nbsp;`/songs`, the&nbsp;`params[:genre]`&nbsp;will be&nbsp;`rock`.

### Segment Constraints

Sometimes you may want to add some constraints on the dynamic segments in a route. For example, you may want to restrict the&nbsp;`id`&nbsp;to three digits. For this, you can pass the&nbsp;`:constraint`&nbsp;option as follows:

```ruby
get 'images/:id', to: 'images#show', constraints: { id: /\d{3}/ }
```

This route would match paths such as&nbsp;`/images/293`, but not&nbsp;`/images/xyz`.

The above route can be succinctly expressed by passing the segment key itself.

```ruby
get 'photos/:id', to: 'photos#show', id: /\d{3}/
```

## Query Strings

A query string is indicated by the first&nbsp;`?`&nbsp;in the URL. It's used to pass additional data to the server.

```ruby
http://example.com/admin?true
```

Rails allows you to handle query strings in a similar way to dynamic segments: by making them accessible in the&nbsp;`params`&nbsp;hash.

Consider the following route:

```ruby
get 'photos/:id', to: 'photos#show'
```

If the user agent sends an HTTP request to the&nbsp;`photos/1?hue=10`, the params hash will contain:

```ruby
params = {
  id: 1,
  hue: 10,
  # ...
}
```

