将CanCanCan用于角色和多个设计模型吗?

时间:2019-03-08 00:18:07

标签: ruby-on-rails ruby devise cancan cancancan

我需要使用CanCanCan来限制所有用户只能查看自己的数据或允许他人查看有限数据的能力。

我尝试了以下操作,但不起作用:

class Ability
  include CanCan::Ability

      def initialize(user)

        user ||= User.new # guest user (not logged in)
        affiliate ||= Affiliate.new # guest user (not logged in)
        # guest ||= U
        #Admin
        if user.admin?
          can :manage, :all

        elsif user.seller?
            can :manage, Listing, user_id: user.id
            can :read, Listing
            can :manage, Order, buyer_id: user.id
            can :manage, Order, seller_id: user.id
            can :manage, StripeAccount, user_id: user.id

            can :manage, BankAccount, user_id: user.id
            can :manage, User, user_id: user.id

        elsif affiliate
            can :manage, User, affiliate_id: affiliate.id
            can :read, Order
            can :manage, StripeAccount, affiliate_id: affiliate.id
            can :manage, Affiliate, affiliate_id: affiliate.id


        #Buyer
        elsif user.buyer?
          can :read, Listing
          can [:create, :read, :edit, :purchases, :update], Order, buyer_id: user.id

        #Guest
        else
          can :read, Listing
          can [:create, :order_confirmation], Order
          # can :create, User
        end
      end
    end 

当我以会员身份登录时,它不会让我查看与affiliate.id相关联的StripeAccount,并且该地址位于模型中。

我有两个模型,用户模型和会员模型。

用户的角色为枚举1,2,3。 (管理员为3) 会员的角色为枚举1,2

我需要为每个设计模型和每个设计模型中的每个角色设置限制。

1 个答案:

答案 0 :(得分:0)

这似乎已经解决了,仍在测试:

private

  def current_ability
    @current_ability ||= Ability.new(current_user, current_affiliate)
  end

然后使用:

def initialize(user, affiliate)