允许多个模型访问一个控制器
Allowing multiple models to access a controller
我有一个正在调用的控制器
before_action :authenticate_user!
开头。但是,我还有一个模型 admin,它应该访问这个控制器,即
before_action :authenticate_admin!
我怎样才能使任何一个都可以访问控制器?
Devise 分别为 User
模型和 Admin
模型提供辅助方法 user_signed_in?
和 admin_signed_in?
。
您可以在ApplicationController
中编写自定义过滤器,并根据需要在具体控制器中应用过滤器。
class ApplicationController < ActionController::Base
...
class AuthorizationException < StandardError
end
rescue_from AuthorizationException do
render text: "Access Denied", status: :unauthorized
end
protected
def authenticate_user_or_admin!
unless user_signed_in? or admin_signed_in?
raise AuthorizationException.new
end
end
end
您现在可以在控制器中使用过滤器 authenticate_user_or_admin!
。
我有一个正在调用的控制器
before_action :authenticate_user!
开头。但是,我还有一个模型 admin,它应该访问这个控制器,即
before_action :authenticate_admin!
我怎样才能使任何一个都可以访问控制器?
Devise 分别为 User
模型和 Admin
模型提供辅助方法 user_signed_in?
和 admin_signed_in?
。
您可以在ApplicationController
中编写自定义过滤器,并根据需要在具体控制器中应用过滤器。
class ApplicationController < ActionController::Base
...
class AuthorizationException < StandardError
end
rescue_from AuthorizationException do
render text: "Access Denied", status: :unauthorized
end
protected
def authenticate_user_or_admin!
unless user_signed_in? or admin_signed_in?
raise AuthorizationException.new
end
end
end
您现在可以在控制器中使用过滤器 authenticate_user_or_admin!
。