2016-01-15 125 views
-1

我试图以下基于ActionDispatch::RemoteIp::GetIp#calculate_ip获取远程IP地址型号

>> ActionDispatch::RemoteIp::GetIp.calculate_ip 

但是做的,我看到这个错误:

!! #<NoMethodError: undefined method `calculate_ip' for ActionDispatch::RemoteIp::GetIp:Class> 

所以现在的问题是,如果采用这种方法有缺陷的,我如何在模型中获得远程IP?

+0

'calculate_ip'是一个实例方法,NOT类方法:) – RAJ

+0

谢谢。那么您对在模型中获取远程IP有什么建议? – Abram

+0

只是想说一个IP地址只在http请求的上下文中才有意义。因此,我认为您必须确定控制器中的IP地址,而不是模型中的IP地址。在测试或后台工作中使用模型时,IP地址是什么? – zwippie

回答

3

转换我的评论到一个答案:

一个IP地址只能发出HTTP请求的上下文中的意义。因此,您必须确定控制器中的IP地址,而不是模型中的IP地址。在测试或后台工作中使用模型时,IP地址是什么?

里面一个控制器,可以让客户端的IP地址为:

request.remote_ip 

现在,您可以将该值赋给一个模型属性:

@object.ip_address = request.remote_ip 
@object.save 
0

的IP地址,最好是能在HTTP请求的上下文中确定,实际上Rails会为你做这件事,并在任何实例化的控制器中提供request.remote_ip的结果。

class SomeController < ApplicationController 
    def some_action 
    remote_ip = request.remote_ip 
    # You can now pass the ip anywhere you'd like to use it 
    end 
end