Search code examples
ruby-on-railsrails-geocoder

Rails - Geocoder Gem : geocoded_by with 2 tables


I'm used to work with the geocoder gem the way I saw in http://railscasts.com/episodes/273-geocoder, but my model is becoming a bit more complex than the given example.

Now, I would like to use 2 models :
- "City", which has a "name" attribute
and
- "Location", which has "latitude", "longitude" and "city_id" attributes

This way, the location will have default latitude and longitude values, and, later, we can precise them.

The question is, in the Location model, how can I specify that the location is geocoded_by the name in the City model ?

I was looking for something simple, like that :

geocoded_by :city, :name

or

geocoded_by self.city.name

Thank you for your help.

Edit: Here are the current models:

class Location< ActiveRecord::Base
  attr_accessible :city_id, :latitude, :longitude
  belongs_to :city
  geocoded_by ??? (how to specify the city.name value ?)
  after_validation :geocode  
end

class City < ActiveRecord::Base
  attr_accessible :name
  has_many :locations
end

Solution

  • Not sure if it works but you could try:

    geocoded_by lambda{ |obj| obj.city.name }
    

    or, if the above doesn't work:

    geocoded_by :city_name
    
    def city_name
      self.city.name
    end