1
votes

When a user logs in to the website I want geocoder to take the current_sign_in_ip and convert it to the usable latitude: longitude: how can I do this?

my User model-

geocoded_by :current_sign_in_ip
after_validation :geocode, :if => :current_sign_in_ip_changed?
1

1 Answers

0
votes

In order to let geocode record down the latitude and longitude. You need to add latitude and longitude fields to your db table. Let say you using users table.

First add the migration

rails generate migration AddLatitudeLongitudeToUsers

Modify the migration as follow

class AddLatitudeLongitudeToUsers < ActiveRecord::Migration
  def change
    add_column :users, :latitude, :float
    add_column :users, :longitude, :float
  end
end

Run rake db:migrate to save the change.

Add the following geocode setting to user model

class User < ActiveRecord::Base
  geocoded_by :current_sign_in_ip
  after_validation :geocode, if: :current_sign_in_ip_changed?
end

As most of us testing and develop app in our local machine, current_sign_in_ip will record down as "127.0.0.1" after you sign in.

You can verify it from rails console rails c

u = User.find_by_email("[email protected]")
u.current_sign_in_ip
u.latitude
u.longitude

To see whether geocoder work or not, let change the ip manually

u.current_sign_in_ip = "199.182.122.98"
u.save
u.latitude
u.longitude

After you sign in, please make sure current_sign_in_ip field has ip record down. Otherwise, the latitude and longitude field will be nil.