[英]How do I get my ability.rb to work properly for my index action?
这是我的ability.rb
样子:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
end
can :manage, Connection, inviter_user_id: user.id
end
end
在我的控制器中,我有:
class ConnectionsController < ApplicationController
load_and_authorize_resource
skip_authorize_resource only: :index
layout 'connections'
def index
@family_tree = current_user.family_tree
@inviter_connections = current_user.inviter_connections.order("updated_at desc")
@invited_connections = current_user.invited_connections.order("updated_at desc")
end
end
在我的application_controller.rb
,我有这个:
rescue_from CanCan::AccessDenied do |exception|
redirect_to authenticated_root_url, :alert => exception.message
end
但是,当我未登录时尝试访问/connections
时,出现此错误:
NoMethodError at /connections
undefined method `family_tree' for nil:NilClass
另外,当我从ability.rb
删除can :manage, Connection
,它实际上使我像期望的那样进入登录页面。
我如何同时工作?
看来您正在使用Devise进行身份验证。 为了在使用devise时进行这种验证,应将其添加到控制器中:
before_action :authenticate_user!
请尝试以下操作:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
else
can :manage, Connection, inviter_user_id: user.id
end
end
end
另外,请注意,您仅是skip_authorize_resource::index,请尝试将其注释掉,看看是否可行。
在控制器的第8行上,当您尚未登录时, current_user
为nil,并且正在其上调用family_tree
。
您需要类似的东西(仅作为示例,这取决于您的需求):
@family_tree = current_user.try(:family_tree) || FamilyTree.new
当您在Ability
删除该行时,它“起作用”的原因是,这删除了查看连接的功能,因此before_filter
在您进入内部index
之前进行重定向。 可能使您绊倒的是Connection
记录的inviter_user_id
为nil
,而User#id
为nil
,因此它授予您进入index
权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.