Problem with accessing a variable in a nested form

I have a nested form in rails view 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>

      

It fails with an error message

undefined method `description' for nil:NilClass

      

Why does invoice_item_number return null object in this partial? Obviously this is defined in some way, because if I change it to something else (for example item_number.description

, then the error message becomes undefined local variable or method

item_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 : number%> both work perfectly well. I have tried a number of solutions such as using

@ invoice_item_number` and explicitly defining the object in the render method, but they didn't work.

Presumably there is a very simple answer to this question.

+2


a source to share


2 answers


Just re-read Ryan scraps post on nested forms http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes and found the answer. It was already in my code, but I didn't understand what was going on. I can access the invoice_item_number object with f.object, so replacing <%= invoice_item_number.description %>

with has <%= f.object.description %>

solved my problem.



+6


a source


how about changing:

<%= invoice_item_number.description %>

      

to



<%= f.label :description %>

      

or if you need a field:

<%= f.text_field :description %>

      

+2


a source







All Articles