我正在从头开始构建用户授权,并且一直在处理用户角色。我被困在权限部分,因为我不知道如何定义它。当我向控制器添加“before_filter:authorize”时,它会在所有页面上显示“”未初始化的常量ApplicationController :: Permission“”错误。
我知道错误是来自我的application_controller.rb文件:
def current_permission
@current_permission || Permission.new(current_user)
end
def authorize
if !current_permission.allow?(params[:controller], params[:action])
redirect_to root_url, alert: "Not authorized."
end
Permission.rb:
Class Permission < Struct.new(:user)
def allow?(controller, action)
if user.nil?
controller == "galleries" && action.in?(%w[index show])
elsif user.admin?
true
else
controller == "galleries" && action != "destroy"
end
end
我不知道如何正确定义我的应用程序中的权限,以便我不会收到该错误。有没有人有任何想法?
答案 0 :(得分:1)
您的Permission
课程有两个问题:
Class
应为class
,小写c
。end
关闭班级。我还必须指出,没有理由重新发明轮子。许多人选择使用cancan或declarative_authorization来做你想要完成的事情。
就个人而言,我喜欢更轻量级的Pundit宝石,它似乎适合你想要完成的事情。