How do I get a client's ip address in Rails?
ruby-on-rails, ruby-on-rails-3
Solution
This looks like code that should be in a model, so I'm assuming that's where this method is. If so, you can't (at least 'out of the box') access the request object from your model as it originates from an HTTP request -- this is also why you get "undefined local variable or method "request" from main" in your console.
If this method is not already in your model I would place it there, then call it from you controller and pass in 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, be aware that "Location.find_by_ip" will return nil if no records are matched.
And, you can issue a request in your console by using app.get "some-url", then you can access the request_ip from request object app.request.remote_ip and use it for testing if needed.
Problem
I have a function in my controller that calls another function form the model that needs to be fed 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 gathered remote.request_ip gives you the ip address, however when I call that function with request.remote_ip the object is nil. If I put in a static ip address though it produces the right output. What would be the correct way to get the ip address if remote.request_ip does not do so? also when I try typing "request.remote_ip" in the console it returns "undefined local variable or method "request" from main"