Problem accessing variable in a nested form partial

Posted by brad on Stack Overflow See other posts from Stack Overflow or by brad
Published on 2010-04-23T06:01:37Z Indexed on 2010/04/23 6:03 UTC
Read the original article Hit count: 299

I have a nested form in a rails view that is called like this

<% f.fields_for :invoice_item_numbers do |item_no_form| %>
    <%= render 'invoice_item_number', :f => item_no_form %>
<% end %>

and the partial (_invoice_item_number.html.erb) looks like this

<div class='invoice_item_numbers'>
<% if f.object.new_record? %>
        <li><%= f.label :item_number %><%= f.text_field :item_number %>
    <%= link_to_function "remove", "$(this).parent().remove()", :class => 'remove_link' %></li>
<% else %>
    <li class="inline"><%= f.label :item_number %><%= f.text_field :item_number %>
    </li><li class="inline"><%= f.label :description %><%= invoice_item_number.description %></li><li><%= f.label :amount %><%= f.text_field :amount %>
    <%= f.check_box '_destroy', :class => 'remove_checkbox' %>
    <%= f.label '_destroy', 'remove', :class => 'remove_label' %></li>
<% end %>
</div>

This fails with the error message

undefined method `description' for nil:NilClass

Why does invoice_item_number return a nil object in this partial? It is obviously being defined somehow because if I change it to something else (e.g. item_number.description then the error message becomes undefined local variable or methoditem_number' for #instead. The invoice_item_number object that is being displayed by this partial is being used perfectly well by the form helpers as<%= f.text_field :item_number %>and<% f.text_field :amount %>both work perfectly well. I have tried a number of solutions such as using@invoice_item_number` and explicitly defining an object in the render method but these have not worked.

Presumably there is a very simple answer to this.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about forms