Friday, March 25, 2016

How to pass custom variables to a partial in Rails 5

Let's say that you want to render the same form partial for creating and editing a project. You can pass a custom value for the button in the form partial like this:

<%= render 'form', project: @project, button_name: 'Create'  %>



You can use the passed in variable in the form partial like this:



<%= form_for(project) do |f| %>
  <% if project.errors.any? %>
   

     

<%= pluralize(project.errors.count, "error") %> prohibited this project from being saved:



     

          <% project.errors.full_messages.each do |message| %>
           
  • <%= message %>

  •       <% end %>
         

   

  <% end %>

    <% if params[:preview_button] %>
      <%= project.description %>
    <% end %>

 

    <%= f.label :name %>
    <%= f.text_field :name %>
 


 

    <%= f.label :description %>
    <%= f.text_area :description %>
 


 

    <%= f.submit button_name %>
    <%= f.submit 'Preview', name:  'preview_button'  %>
   
 

<% end %>