当访问者访问我的app rails时,想要调用每次都会执行的方法

时间:2015-03-23 06:34:18

标签: ruby-on-rails ruby-on-rails-4

当访问者访问我的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  

1 个答案:

答案 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方法就会每次调用。