Using Rails URL Helpers: Refactoring Your Paths

Joshua McArthur
2 min readJul 9, 2020

Using URL helpers in Rails is a good way to simplify the path designation process to provide yourself with both more easily readable code and practical paths that are more readily adaptable to changes in the internal code. Because they are methods as opposed to strings, it applies to the code — no matter what it is — so often won’t require a change to adapt to altered code. Furthermore, it makes the writing process easier on the programmer by cutting out the necessity for string interpolation and offering the use of method based arguments. They also translate into HTML-friendly paths more directly and do not encounter difficulties one might encounter when translating code that contains unusual characters that are more difficult to read, such as spaces, &, and %.

If, for example, we are working with an application with an MVC for posts, which contains index and show actions, we will have a route call that looks like:

resources :posts, only: [:index, :show]

This gives us our standard Rails route with our four standard components:

posts   GET  /posts(.:format)       posts#index
post GET /posts/:id(.:format) posts#show

This contains 1) out helper method prefix, 2) the HTTP verb, 3) the path, and 4) the controller and action written as [controller]#[action].

Using the link_to Method and Refactoring an Index Page

Say we start with an index page that links to the show page, that appears like this:

<% @posts.each do |post| %>
<div><a href='<% "/posts/#{post.id}" %>'><%= post.title %></a>
</div>
<% end %>

This will give us a show page that displays a clickable link to the post id that appears at the post’s title. We can clean this up using link_to eliminate the use of multiple ERB calls on the same line by instead writing it as (the changes will be marked in bold):

<% @posts.each do |post| %>
<div><%= link_to post.title, "/posts/#{post.id}" %>'></a></div>
<% end %>

and refactoring the string interpolation using post_path and the post argument:

<% @posts.each do |post| %>
<div><%= link_to post.title, post_path(post.id) %>'></a></div>
<% end %>

and then further refactor it because Rails is equipped to recognize that the post argument automatically uses the id attribute:

<% @posts.each do |post| %>
<div><%= link_to post.title, post_path(post) %>'></a></div>
<% end %>

Source: https://learn.co/tracks/online-software-engineering-structured/rails/intro-to-actionview/rails-url-helpers

--

--