Rails - CanCanCan, Rolify, Define - Defining Abilities for associated model
<p>I am using Devise for Authentication &amp; CanCanCan / Rolify for Authorisation.</p>

<p>I’m wanting to restrict each model’s record, to the user who created it, via the various associations.</p>

<p>I.e. /sales/1 should only be viewable by the User who belongs_to the organisation that has the sale.</p>

<pre><code>User
   has_many :organisations

Organisation
   belongs_to :user
   has_many :sales

Sale
   belongs_to :organisation
   has_many :payments

Payment
   belongs_to :sale
</code></pre>

<p>Restricting the Organisation to the User who belongs to it is straight forward:</p>

<pre><code>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 =&gt; user.id
      end
   end
end
</code></pre>

<p>How can I achieve the same thing for an associated Sale and subsequently an associated Payment?</p>

<pre><code>can [:manage], Sale, ?

can [:manage], Payment, ?
</code></pre>

<p>Note: Rails 5.0.0.1, Ruby 2.3.1</p>