Search code examples
ruby-on-railssegment

Rails current_user ip returning nil for unknown reason


In my application controller, i have this code

 def user_ip
  request.remote_ip
  @remote_ip = current_user.request.env["HTTP_X_FORWARDED_FOR"]
  end

what i'm trying to do is add the current_users IP address to an analytics system, which is in a different static_controller.rb with the following code

def matrimonials

  Analytics.identify(
    user_id: current_user.id,
    traits: { email: "#{ current_user.email }", ip: @remote_ip, friends: 100 },
    context: {ip: @remote_ip }
    )


  Analytics.track(
    user_id: current_user.id,
    user_email: current_user.email,
    event: 'Viewed Matrimonials',
    properties: {
      name: 'Matrimonials page'
    }
  ) if user_signed_in?

end

in my analytics debugger, i get this result:

Analytics.identify(
  user_id: '1',
  traits: {
    email: 'test@test.com',
    friends: 100,
    **ip: nil**
  }
)

why is the ip nil? i set the request in the application controller, from which static controller inherits from..


Solution

  • You can try this : Define you user_ip as a helper method and use it in you matrimonials method.

    class ApplicationController < ActionController::Base
      helper_method :user_ip
    
      def user_ip
        #...
      end
    end
    
    
    def matrimonials
      #...
      context: {ip: user_ip }
    end