DEV Community

Eulis
Eulis

Posted on

What's a Rails Partial?

In a Rails Application, partial templates are a way of breaking down the view rendering processes into small bits. Partials allow us to reuse a block of code in many of others files and templates.

  • Partial are easily created by making a file _form.html.erb within the app/views/tags/_form.html.erb.

  • To use or render a Partial, we need to pass the render method within a view <%= render 'form' %>

  • We leave out the underscore when rendering the partial.

  • Important: To Render a partial in another file, we must use the path.

  • <%= render partial: 'form', locals: { tag: @tag } %>

Partial are a great way to practice the DRY philosophy.
Reference

The example below is an example of a form partial file.

<%= form_with(model: [@tag.bookmark, @tag]) do |f| %>

    <% if !@tag.bookmark %>
    <%= f.label :bookmark_id, "Bookmark:" %>
    <%= f.collection_select :bookmark_id, Bookmark.order(:name), :id, :name %>
    <% else %>
    <%= f.hidden_field :bookmark_id %>
    <% end %>
    <br><br>

    <%= f.label :name, 'Tag Name:' %>
    <%= f.text_field :name %><br><br>
    <%= f.submit %>
<% end %>
Enter fullscreen mode Exit fullscreen mode
  • This Was Just a quick Overview of partials within a Ruby on Rails Application, Please check out the reference to the rails docs linked above the code block as this post only explain the basic use of form partials.
  • NOTE: This is one of 30 blogs that I would be attempting to write over the next 30 days to improve my writing skills.

Top comments (0)