首页 > 解决方案 > 使用 CanCanCan - 我显然在做一些明显错误的事情

问题描述

晚上好,

CanCanCan 很棒;但是,我认为我遗漏了一些非常明显的东西,因为我的模型逻辑非常简单。

第 1 步和第 3 步有效。但是,第 2 步不起作用 - 如果另一个用户已登录,则尝试查看某个东西;他们看到“CanCan::AccessDenied”,除非这是他们的事。

能力.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

能力.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 %>

更多阅读官方文档

标签: ruby-on-railscancancan

解决方案


在我看来,我的观点是:

  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

用这篇文章试过,来源


推荐阅读