我想在application_controller.rb中使用before_action,然后使用一些skip_before_action
来防止在用户登录之前调用某些网站。
但我的application_controller.erb中定义的函数未被调用...
application_controller.erb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
layout "application"
before_action :user_logged_in, :set_locale
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
# Prüft ob ein Nutzer eingeloggt ist.
def user_logged_in
puts "HA"
if session[:user_id].nil?
flash[:error] = "error"
redirect_to :controller => :startsites, :action => :index
else
flash[:error] = "ok"
redirect_to :controller => :startsites, :action => :index
end
end
end
我的服务器控制台中未打印user_logged_in
中的“HA”。所以我觉得这个功能还没有调用..但为什么呢?
在某些控制器中,我试图使用它:
class MoviesController < ActionController::Base
skip_before_action :user_logged_in, only: [:index, :show]
also not working ... why?
非常感谢你的帮助。
答案 0 :(得分:2)
您正试图通过ActionController
致电。当你建造它时,它不可能那样。
ActionController::Base
-ApplicationController #your method in this controller
ActionController::Base
-MoviesController #yr trying to skip it right here
要跳过它,你必须继承如下:
ActionController::Base
-ApplicationController #yr method is here
--MoviesController #it will find that method and skip it.
<强>控制器强>
# application_controller.rb
class ApplicationController < ActionController::Base
end
# movies_controller.rb
class MoviesController < ApplicationController
end