Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book