Extracting Partials

We’ve already written a form for creating new products. Wouldn’t it be nice if we could reuse that for edit and update? We can, using a feature called “partials” that allows you to reuse a view in multiple places.

We can move the form into a file called . The filename starts with an underscore to denote this is a partial.

We also want to replace any instance variables with a local variable, which we can define when we render the partial. We’ll do this by replacing @product with product.

<%= form_with model: product do |form| %>
<div>
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>

To use this partial in our view, we can replace the form with a render call:

<h1>New product</h1>
<%= render "form", product: @product %>
<%= link_to "Cancel", products_path %>

The edit view becomes almost the exact same thing thanks to the form partial. Let’s create with the following:

<h1>Edit product</h1>
<%= render "form", product: @product %>
<%= link_to "Cancel", @product %>

To learn more about view partials, check out the Action View Guide.

Powered by WebContainers
Files
Preparing Environment
  • Preparing Ruby runtime
  • Prepare development database