O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 /> <%= f.text_field ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required