Rails views helper best practices


Views Should Be Simple

Bad Example

<!-- app/views/posts/show.html.erb -->
<% post = Post.find(params[:id]) %>
<h1><%= post.title %></h1>
  • Issue: Including ActiveRecord calls directly in views couples them with the model layer, leading to a monolithic, harder to maintain view.
  • File: app/views/posts/show.html.erb

Good Example

<!-- app/views/posts/show.html.erb -->
<h1><%= @post.title %></h1>
  • Setup: Load @post in the controller action.
  • File: app/views/posts/show.html.erb

Logic Should Reside in Helpers or Models

Move Complex Presentational Logic to Helpers

<!-- app/views/users/show.html.erb -->
<p>
User since: <%= render_user_since(@user.created_at) %>
</p>

Example of using a helper method in place of Ruby logic in the view.

# app/helpers/user_helper.rb
module UserHelper
  def render_user_since(date)
    time_ago_in_words(date) + " ago"
  end
end
  • Benefit: Simplifies view by abstracting logic into testable methods.
  • File: app/helpers/user_helper.rb, app/views/users/show.html.erb

Use Partials for Reused Components

<!-- app/views/comments/_comment.html.erb -->
<p><%= comment.body %></p>

Create a simple partial for comments.

<!-- app/views/posts/show.html.erb -->
<%= render @post.comments %>

Automatically renders the _comment.html.erb partial for each item in @post.comments.

  • Advantage: Reduces duplication and encourages component reusability.
  • File: app/views/comments/_comment.html.erb, app/views/posts/show.html.erb

Use Built-in Helpers and Forms

Avoid Reinventing Helpers

<!-- Use Rails' built-in helpers for forms -->
<%= form_for @user do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.submit "Save" %>
<% end %>

Leverages form_for helper to simplify form markup.

  • File: app/views/users/_form.html.erb

Rails comes with a vast array of view helpers designed to simplify code, adhere to conventions, and improve maintainability.

Conclusion

Keep the view layer clean with helpers, partials, and built-in functionality effectively.

This approach decreases complexity and future maintenance costs.


Related posts

Free Training By Email:
Building a Rails Engine

We will send udpates but we care about your data.
No spams.

Back to homepage