Rails - CanCanCan、Rolify、Define - 为关联模型定义能力

Rails - CanCanCan, Rolify, Define - Defining Abilities for associated model

我正在使用 Devise 进行身份验证,使用 CanCanCan / Rolify 进行授权。

我想通过各种关联将每个模型的记录限制为创建它的用户。

即/sales/1 只有 belongs_to 进行销售的组织的用户才能看到。

User
   has_many :organisations

Organisation
   belongs_to :user
   has_many :sales

Sale
   belongs_to :organisation
   has_many :payments

Payment
   belongs_to :sale

将组织限制为属于它的用户很简单:

class Ability
   include CanCan::Ability

   def initialize(user)
      user ||= User.new # guest user (not logged in)
      if user.has_role? :admin
        can :manage, :all
      elsif user.has_role? :standard
        can [:create, :read, :update, :destroy], Organisation, :user_id => user.id
      end
   end
end

我怎样才能为关联的销售和随后的关联付款实现相同的目标?

can [:manage], Sale, ?

can [:manage], Payment, ?

注:Rails5.0.0.1,Ruby2.3.1

您可以在payment.rb

中添加关联
 belongs_to :sale
 has_one :organisation, through: :sale

然后你可以加入ability.rb

 can :manage, Sale, :organisation => { :user_id => user.id }
 can :manage, Payment, :organisation => { :user_id => user.id }