Search code examples
ruby-on-railsdatabase-migrationgoogle-geocodernomethoderrorgoogle-maps-static-api

NoMethodError in #show view. Undefined method 'latitude'. Geocoder to get lat and long


I'm trying to use Geocoder to populate the latitude and longitude for a given address of a restaurant inputed by the user. My show page is giving me the following error:

NoMethodError in Restaurants#show

undefined method `latitude' for #<Restaurant:...

I've run:

$rails generate latlong migration latitude:float longitude:float
$rake db:migrate 

I've updated the restaurant params to include latitude and longitude.

The part referencing url in the show file looks like this:

<p>
<strong>Where's it at?</strong>
<%= image_tag "http://maps.google.com/maps/api/staticmap?size=450x300&sensor=false&zoom=16&markers=#{@restaurant.latitude}%2C#{@restaurant.longitude}" %>

</p>

Here's my migrate file:

class Latlong < ActiveRecord::Migration
  def change
    add_column :restaurants, :latitude, :float
    add_column :restaurants, :longitude, :float
  end
end

and my model looks like this:

class Restaurant < ActiveRecord::Base

    mount_uploader :picture, PictureUploader
    mount_uploader :menu, MenuUploader 

    geocoded_by :address
    after_validation :geocode  

end 

Solution

  • You've made wrong migration, so:

    • Run rake db:rollback - to return back and have clean DB.
    • Run rails g migration AddLatitudeAndLongitudeToRestaurants latitude:float longitude:float - proper migration (due to gem documentation you have to add new columns to the existing model, not create almost separate and new table in DB).
    • Run rake db:migrate.