2016-01-15 122 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