How to get client IP address in Rails?

I have a function in my controller that calls another form of function that needs to be passed to the ip address

def get_location_users if current_user return current_user.location_users else l = Location.find_by_ip(request.remote_ip) lu = LocationUser.new({:location_id => l.id, :radius => Setting.get("default_radius").to_i}) return [lu] end end 

from what I compiled remote.request_ip gives you an IP address, however, when I call this function with request.remote_ip, the object is zero. If I set a static IP address, it will give the correct output. What would be the correct way to get the IP address if remote.request_ip does not do this?

also, when I try to enter "request.remote_ip" in the console, it returns the "undefined local variable or the" request "method from the main"

+4
source share
3 answers

It looks like the code that should be in the model, so I guess where this method is. If so, you cannot (at least "out of the box") access the request object from your model, since it comes from an HTTP request - this is also the reason you get a "<90" local variable or method "request", from the main "in the console.

If this method was not in your model yet, I would place it there, then call it from the controller and pass it to request.remote_ip as an argument.

 def get_location_users(the_ip) if current_user return current_user.location_users else l = Location.find_by_ip(the_ip) lu = LocationUser.new({:location_id => l.id, :radius => Setting.get("default_radius").to_i}) return [lu] end end 

Then in your controller ::

 SomeModel.get_location_users(request.remote_ip) 

Also, keep in mind that "Location.find_by_ip" will return null if the entries do not match.

And you can send the request to the console using app.get "some-url" , then you can access request_ip from the request object app.request.remote_ip and use it for testing if necessary.

+3
source

Do you have a typo in your question or are you really calling remote.request_ip?

The correct method would be request.remote_ip

+6
source
  • HTTP requests: request.ip (as Sebastian noted in his answer)

    also available as: request.env['action_dispatch.request_id']

  • HTTPS requests: request.env['HTTP_X_FORWARDED_FOR'].split(/,/).try(:first)

+2
source

Source: https://habr.com/ru/post/1447542/


All Articles