Lesson Monday

Several of our views use repeated code. Specifically, our forms for creating and updating albums look exactly the same. The same goes for our forms for songs as well. Instead of repeating the same code, we can use partials to DRY up our views. A partial allows us to take a piece of code and drop it into views where it is needed.

Let's update our forms and error messages to use partials. First, we'll start by extracting our errors message from the forms where it's used. It should be included with all of our album and song forms, which means it's exactly the same in four places. In a larger application with more forms, this piece of code would be even more repetitive.

We want this partial to be available to all views so we will put it in the views/layouts folder. The correct naming convention in Rails is always to begin the name of a partial with an underscore. For example, we'll use _errors.html.erb, rather than errors.html.erb.

app/views/layouts/_errors.html.erb
<% if object.errors.any? %>
  <h3>Please fix these errors:</h3>
  <ul>
    <% object.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
  </ul>
<% end %>

Then we'll put this partial inside another partial. This second partial is for the form itself.

app/views/layouts/_album_form.html.erb
<%= render "layouts/errors", :object => @album %>

<%= form_for @album do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :genre %>
  <%= f.text_field :genre %>
  <%= f.submit %>
<% end %>

Now we can update our views for editing and creating an album to look like this:

app/views/albums/new.html.erb
<h1>New Album</h1>

<%= render "layouts/album_form" %>
app/views/albums/edit.html.erb
<h1>Edit Album</h1>

<%= render "layouts/album_form" %>

Lesson 19 of 34
Last updated July 14, 2022