Search code examples
ruby-on-railsformspartials

Undefined Local Variable or Method `f' In a view partial


This seems like such a stupid, easy fix (it probably is) but I've been searching SO and other areas on the web with no luck. I'm getting an undefined method local variable error 'f' within my partial used in my view. I'm assuming that the "do block" is ending somehow prior to reaching the partial but I'm not 100% certain.

Partial

<% if user_admin_or_premium? %>
  <div class="form-group">
    <%= f.label :private, class: 'checkbox' do %>
      <%= f.check_box :private, :true %> Private Wiki?
    <% end %>
  </div>
<% end %>

View

<div class="col-md-8">
  <%= form_for @wiki do |f| %>
    <div class="form-group">
      <%= f.label :title %>
      <%= f.text_field :title, class: 'form-control', placeholder: "Enter Wiki Title" %>
    </div>
    <div class="form-group">
      <%= f.label :body %>
      <%= f.text_area :body, rows: 10, class: 'form-control', placeholder: "Enter Wiki Body" %>
    </div>
    <%= render partial: "wikis/form", f: f  %>
    <div class="form-group">
      <%= f.submit "Save", class: 'btn btn-success' %>
    </div>
  <% end %>
</div>

Full Error

NameError in Wikis#new

undefined local variable or method `f'

<% if user_admin_or_premium? %>
  <div class="form-group">
    <%= f.label :private, class: 'checkbox' do %>
      <%= f.check_box :private, :true %> Private Wiki?
    <% end %>
  </div>

Solution

  • Omit the partial: key from your render function:

    <%= render "wikis/form", f: f %>

    Easy fix, but certainly not obvious, I've been stumped by the same issue before. The above statement is equivalent to the following:

    <%= render partial: "wikis/form", locals: { f: f } %>