加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails中获取客户端的IP地址?

发布时间:2020-12-17 04:00:45 所属栏目:百科 来源:网络整理
导读:我在我的控制器中有一个函数,它调用另一个函数来形成需要输入ip地址的模型 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,:rad
我在我的控制器中有一个函数,它调用另一个函数来形成需要输入ip地址的模型

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

从我收集的remote.request_ip给你ip地址,但是当我用request.remote_ip调用该函数时,对象是nil.如果我输入静态IP地址虽然它产生正确的输出.如果remote.request_ip不这样做,获取IP地址的正确方法是什么?

当我尝试在控制台中输入“request.remote_ip”时,它会从主“返回”未定义的局部变量或方法“请求”

解决方法

这看起来像应该在模型中的代码,所以我假设这是该方法的位置.如果是这样,你不能(至少“开箱即用”)从你的模型访问请求对象,因为它来自HTTP请求 – 这也是你从主要获得“未定义的局部变量或方法”请求的原因“在你的控制台中.

如果你的模型中没有这个方法,我会把它放在那里,然后从你的控制器调用它并传入request.remote_ip作为参数.

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

然后,在你的控制器::

SomeModel.get_location_users(request.remote_ip)

另外,请注意,如果没有匹配的记录,“Location.find_by_ip”将返回nil.

并且,您可以使用app.get“some-url”在控制台中发出请求,然后您可以从请求对象app.request.remote_ip访问request_ip,并在需要时使用它进行测试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读