Putting the Form Body in a Partial

All the changes to the new.html.erb form are great, but there’s still one annoying problem: the edit.html.erb form needs to be consistent with new.html.erb. For some reason, the Rails scaffolding ignores the “Don’t Repeat Yourself” mantra, and puts duplicate code into both pages.

Fortunately, Rails also provides a mechanism that lets you avoid this duplication. Example 6-10 shows the new version of the new.html.erb form, and Example 6-11 shows the new version of the edit.html.erb form.

Example 6-10. new.html.erb, using a partial

<h1>New person</h1>

<%= render :partial => 'form' %>

<%= link_to 'Back', people_path %>

Example 6-11. edit.html.erb, using a partial

<h1>Editing person</h1>

<%= render :partial => 'form' %>

<%= link_to 'Show', @person %> |
<%= link_to 'Back', people_path %>

Where’d all the actual content go? Into another file in the same app/views/people directory, called _form.html.erb, shown in Example 6-12. The underscore at the start of the name tells Rails that this is a file containing a partial, and when Rails goes looking for a partial referenced from either of these .html.erb files, it will seek _form.html.erb. Example 6-12 skips any reference to either new or edited material—which is fine, since the original code worked either way.

Example 6-12. The _form.html.erb file’s contents

<%= error_messages_for :person %> <% form_for(@person) do |f| %> <p> <b>Name</b><br /> <%= f.text_field :name %> </p> <p> <b>Secret</b><br ...

Get Learning Rails: Live Edition 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.