晚上好,
CanCanCan很棒;但是,我认为我缺少明显的东西,因为我的模型逻辑很简单。
第1步和第3步起作用。但是,第2步不起作用-如果另一个用户登录,则尝试查看事物;他们会看到“ CanCan :: AccessDenied”,除非这是他们的事情。
Ability.rb
if user.present?
can :manage, List, user_id: user.id
else
can [:read, :search], List
end
上面的代码段中user.present?
是否已链接/锁定到current_user?我试过省略.present吗?但是,这仍然呈现CanCan :: AccessDenied。
[在发生此意外错误时,我认为类似以下内容的方法会起作用,可惜没有。
if user.present?
can :manage, List, user_id: user.id
elsif @list.find(params[:id]).user != user
can [:read], List
else
can [:read, :search], List
end
对于后代,请在Roman Alekseiev提供的内容之上找到我的解决方案。
应用程序控制器
class ApplicationController < ActionController::Base
load_and_authorize_resource :parent
load_and_authorize_resource :child, through: :parent
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= ::User.new
if user.new_record?
can [:read, :search], Parent
can [:read], Child
else
can [:read, :search], ::Parent
can [:read, :create, :delete], Child
can :manage, Parent, user_id: user.id
end
end
如何在视图中使用功能,例如显示。
<% if can? :create, @parent => Child %>
present the child markup/content
<% end %>
从我的角度来看:
def initialize(user)
user ||= ::User.new
if user.new_record?
can [:read, :search] ::List
else
can [:read, :comment], ::List
can :manage, ::List, user_id: user.id
end
[本文尝试过,source