当访问者访问我的app rails时,想要调用每次都会执行的方法。我应该在哪里定义它,在应用程序控制器中尝试。
def get_ip
if request.remote_ip == '127.0.0.1'
# Hard coded remote address
'123.45.67.89'
else
request.remote_ip
end
end
答案 0 :(得分:3)
你说得对,你应该只在ApplicationController中定义这个方法,并在before_action
中调用它。像:
class ApplicationController < ActionController::Base
before_action :get_ip
def get_ip
if request.remote_ip == '127.0.0.1'
# Hard coded remote address
'123.45.67.89'
else
request.remote_ip
end
end
end
只要请求点击get_ip
或任何从ApplicationController
继承的控制器的任何操作, ApplicationController
方法就会每次调用。