Bye
Bye

Reputation: 768

Rails :How to move code from view to partial file

In edit.html.erb

 <% if material.look %>
        <%= form_for material do |f|%>
        <% if material.approval = "1" %>
          <%= f.hidden_field :date,value: Date.today %>
        <% end %>
        <%= f.hidden_field :approval_amount, value: 0 %>
        <%= f.hidden_field :approval_amount_percentage, value: 0 %>
        <%= f.submit 'yes' %>
    <% end %>
    <%= form_for material do |f|%>
        <%= f.hidden_field :approval_amount, value: 0 %>
        <%= f.hidden_field :approval_amount_percentage, value: 0 %>
        <%= f.submit 'no' %>
        <% end %>
    <% end %>

Code in two forms are duplicate, so I want to move them to partial file, In _material_form.html.erb I code like this

<%= f.hidden_field :approval_amount, value: 0 %>
<%= f.hidden_field :approval_amount_percentage, value: 0 %>

In edit.html.erb, I modifies duplicate code

   <% if material.look %>
        <%= form_for material do |f|%>
        <% if material.approval = "1" %>
          <%= f.hidden_field :date,value: Date.today %>
        <% end %>
        <%= render 'material_form'%>
        <%= f.submit 'yes' %>
    <% end %>
    <%= form_for material do |f|%>
        <%= render 'material_form'%>
        <%= f.submit 'no' %>
        <% end %>
    <% end %>

However, it shows an error

undefined local variable or method `f' for

What causes the error and how to fix it ? Thanks.

Upvotes: 0

Views: 75

Answers (1)

Nick Tomlin
Nick Tomlin

Reputation: 29221

Your form, assigned to the variable f is out of scope in your partial. To use it, you'll need to pass f in as a local value to your partial:

<%= render 'material_form', f: f%>

The rails documentation on partials is quite helpful; you can also dig into the action renderer documentation if you want to go deeper.

Upvotes: 2

Related Questions