undefined method `coordinates' for nil:NilClass

I'm new to Rails and trying to figure out an issue with a Rails 2.3.14 site. The problem is this store locator i'm trying to fix keeps returning

undefined method `coordinates' for nil:NilClass

when it can't find a store within the distance parameters. If it finds one then it works ok.

Here is the current code i'm trying to work with in my controller

  @map = GMap.new("locations-gmap-div", "locationsGMap")
  @map.control_init(:large_map => true, :map_type => true)
  @mapp.center_zoom_init(@locations.first.coordinates, 8)

This is what I tried to do with my code. I'm still very new to Rails so I apologize if i'm going way off field here.

 @map = GMap.new("locations-gmap-div", "locationsGMap")
 @map.control_init(:large_map => true, :map_type => true)

if @map.center_zoom_init(@locations.first.coordinates,8).nil?
    flash[:error] = 'Sorry, we could not find any stores matching that criteria.'  
    redirect_to store_locator_path          
else
    @map.center_zoom_init(@locations.first.coordinates,8)

end

Any help would be greatly appriciated.


ANSWERS:


Its failing because the @locations are empty.

@locations will return []

@locations.first will return nil

nil.coordinates raises undefined method `coordinates' for nil:NilClass

if @locations.empty?
    flash[:error] = 'Sorry, we could not find any stores matching that criteria.'  
    redirect_to store_locator_path          
else
    @map = GMap.new("locations-gmap-div", "locationsGMap")
    @map.control_init(:large_map => true, :map_type => true)
    @map.center_zoom_init(@locations.first.coordinates,8)
end

You haven't initialized @locations.first. The program seems to be trying to access the coordinates of something that doesn't exist (hence why the exception is on nil:NilClass).



 MORE:


 ? Undefined Method in ruby on rails
 ? Undefined method, avatar and name for nil:NilClass
 ? undefined method `premium?' for nil:NilClass
 ? undefined method `default_image' for nil:NilClass
 ? C# WinForms - Determine when void method returns
 ? C# - Unable to add item to listview from method invoked from class
 ? GCC : Return statement from a void function in C
 ? How to call objective c method from c method iOS
 ? Creating multiple choice for user
 ? Does "return;" at the end of a void method in Java have ANY impact on performance?