Match HTTP Methods with current_page?

When building a Rails app, you often need to create navigation links that highlight the current page. However, Rails’ default current_page? helper only works with GET and HEAD requests. This can be problematic when dealing with forms or actions that use other HTTP methods like POST, PUT, or PATCH. This feature was introduced in this PR

The Problem

For example, if you have a page for viewing posts and another for creating posts, both share the same URL (/posts). The only difference is the HTTP method used (GET for viewing and POST for creating). With the default current_page? helper, it’s difficult to highlight the correct navigation link when a user submits a form to create a post.

The Solution

Rails now allows you to pass a method argument to current_page?, enabling you to match specific HTTP methods when checking the current page. This means you can distinguish between actions that share the same URL but differ by HTTP method.

Here’s how to use it:

1
2
3
4
5
6
7
8
<ul class="nav nav-tabs">
  <li class="nav-item">
    <%= link_to "All posts", posts_path, class: ["nav-link", { active: current_page?(posts_path) }] %>
  </li>
  <li class="nav-item">
    <%= link_to "Create post", new_post_path, class: ["nav-link", { active: current_page?(new_post_path) || current_page?(posts_path, method: :post) }] %>
  </li>
</ul>

Why It Matters

This simple addition makes it easier to highlight the right link, whether you’re viewing posts (GET /posts) or creating a new post (POST /posts). It improves your app’s navigation and helps you avoid unnecessary workarounds.

By adding support for HTTP methods in current_page?, Rails makes it simpler to handle navigation for actions that share the same URL. If you’re working with forms or actions that use multiple HTTP methods, this feature will save you time and help create cleaner, more intuitive navigation.