2
votes

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
2
I tried to answer your question, but if you are geocoding by the name of the city, shouldn't lat and lon be stored in the cities table? I mean all locations in a city will have the same lat/lon. You might as well store it in the cities table instead of locations. - Mischa

2 Answers

2
votes

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
0
votes

You will need to set up a has_many association between your two models.

This guide show you how: http://guides.rubyonrails.org/association_basics.html