5.7. Adding Partials

new.html.erb and edit.html.erb both have the code that generates their forms in common. Rails provides partials in order to reuse code and remove repetition, thereby allowing you to include a partial in other view templates. Partials can be spotted thanks to the underscore prefix on their file name (for example, _person.html.erb).

Go ahead and create an empty _form.html.erb file in app\views\articles. In this file you'll want to include the common snippet of code between the new and edit forms. As such you could copy in _form.html.erb the following code:

<% form_for(@article) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.label :published %><br />
    <%= f.check_box :published %>
</p>
  <p>
    <%= f.label :published_at %><br />
    <%= f.datetime_select :published_at %>
  </p>
  <p>
    <%= f.submit "Update" %>
  </p>
<% end %>

The only problem with this is the value of the Submit button, which is different in the two forms. One is Create and the other says Update. To solve this you can use a local variable (that is, button_value) instead of a string literal (for example, "Create"). You can also change the instance variable @article into a simple variable that's local to the partial, to improve encapsulation.

Copy the following code into _form.html.erb:

<% form_for(article) do |f| %> <%= f.error_messages %> <p> <%= f.label :title %><br /> <%= f.text_field :title ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.