Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a client's ip address in Rails?

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"

like image 400
xxyyxx Avatar asked Dec 20 '22 13:12

xxyyxx


1 Answers

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

The correct method would be request.remote_ip

like image 146
bob Avatar answered Jan 08 '23 03:01

bob