Search code examples
ruby-on-railsrails-geocoder

How should I use the request.ip accessor from Geocoder to get user current ip?


I am having a difficult time finding how to use Geocoder gem on my Rails app to get and save the IP address when creating a new instance of User.

Geocoder has some useful functionalities such as accessors to get current ip location and some other locations information but I'm very new with Rails and it would have been perfect if the documentation had a bit more guidance :-)

As long as I'm using ActiveRecord I started by creating the following migration:

rails generate migration AddIpAddressToUser ip_address:float       

Then I've added this into app/models/user.rb

geocoded_by :ip_address,
  :latitude => :lat, :longitude => :lon
after_validation :geocode

I ran the migration to add these modification on schema.rb:

rails db:migrate            

Now there is the current schema of User model: User.rb has a latitude, longitude and ip_address on its schema.

Being there how could I use the following methods ?

  1. request.ip
  2. request.location

Solution

  • In Rails models are not request aware. So to assign the IP to the user you need to do it from the controller:

    class UserController < ApplicationController
      def create
        @user = User.new(user_params) do |u|
          u.ip_address = request.location
        end
        # ...
      end
    end
    

    If you are using Devise you can just override the build_resource method:

    # Adds request IP to the user to determine location.
    class MyRegistrationsController < Devise::RegistrationsController
      def build_resource(hash={})
        super(hash.merge(ip_address: request.location))
      end
    end
    
    # routes.rb
    devise_for :users, controllers: { registrations: "my_registrations"}