The error occurred while evaluating nil.each

I'm leaving some fields empty and after i sibmited it shows me teh
following error,

# THIS IS THE ERROR THAT IT DISPLAYS

NoMethodError in Item_packages#create

Showing item_packages/_form.erb where line #3 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

Extracted source (around line #3):

1: <script language=javascript>
2: function select_html_code(the_id){
3: <% for measurement_formats in @measurement_formats %>
4: if(the_id=='<%= measurement_formats.id %>'){
5: document.getElementById('<%= measurement_formats.id
%>').style.position='static'
6: document.getElementById('<%= measurement_formats.id
%>').style.visibility='visible'

# THIS IS MY CONTROLLER:

def new
    @item_package = ItemPackage.new(:package_color_id =>
params[:package_color_id])
    @measurement_formats = MeasurementFormat.find(:all)

    respond_to do |format|
      format.html # new.html.erb
      format.xml { render :xml => @item_package }
    end
  end

the weird thing is that if i fill out the entire form,
it'll show no problems?
any idea to this weird problem?

thanks in advanced

the weird thing is that if i fill out the entire form,
it'll show no problems?
any idea to this weird problem?

If the problem is the create action, it would make sense to show us
the code for the create action, not the new action. My guess is that
in your create action you are following the standard pattern of
rerendering the new template if validation fails. However, in your
create action you don't initialize @measurement_formats, hence the
error.

Fred

And, since the nil.each might be a mystery to a nuby, let me point out that:

for measurement_formats in @measurement_formats
#…
end

is just Ruby syntactic sugar for

@measurement_formats.each do | measurement_formats |

  #...

end

BTW I’d suggest renaming the local measurement_formats (without the @) to measurement_format in either case, since it’s going to be a single measurement_format at any given time.