Most (or even all) pages in your Rails application have the same sidebar content, but just one needs to show something different? On your login and registration pages, you don’t want to show the last five books/movies/events, but a marketing text why people should signup for your site? You’re currently using an if/elsif/else statement to switch content based on the controller’s name?

Time to learn about Rails’ Template Inheritance. Your application layout probably looks something like this right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# app/views/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>My Rails Application</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div class="container">
      <div class="col col-main">
        <%= yield %>
      </div>

      <div class="col col-sidebar">
        <%- if controller_name == 'registrations' %>
          Users will only see this when on a registration page.
        <%- elsif controller_name == 'sessions' %>
          Users will only see this when on a session page.
        <%- else %>
          Users will see this all other times.
        <% end %>
      </div>
    </div>
  </body>
</html>

Instead of rendering the sidebar’s content inline, let’s render a partial:

1
2
3
4
5
# app/views/application.html.erb
...
<div class="col col-sidebar">
  <%= render 'sidebar' %>
</div>

Now add a _sidebar.html.erb partial in the following directories: app/views/registrations, app/views/sessions, and app/views/application:

1
2
# app/views/registrations/_sidebar.html.erb
Users will only see this when on a registration page.
1
2
# app/views/sessions/_sidebar.html.erb
Users will only see this when on a session page.
1
2
# app/views/application/_sidebar.html.erb
Users will see this all other times.