shriyog
shriyog

Reputation: 958

How to Geocode address from multiple models?

I need to geocode user's address into latitude & longitude to store in database.

Addresses table

country_id: int
state_id: int
local_address: string
latitude: float
longitude: float

I have separate countries and states tables. So, to get lat & long values I need something like this:

geocoded_by :address 
def address
  [local_address, state, country].compact.join(', ')
end

But the problem is, this is done in model (Address class) and I need to access other tables: countries & states.

So, can't figure a way out. Any working suggestions are appreciated.

Upvotes: 0

Views: 261

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

In your model you need to have the association to your countries and states tables I am assuming that you are saving the state id and country_id

class User < ActiveRecord::Base
  belongs_to :state
  belongs_to :country

  geocoded_by :address 
  def address
    [local_address, state.name, country.name].compact.join(', ')
  end
end

Upvotes: 4

Related Questions