title: Rails/Cancancan: Define ability with a complex/scoped query
body: <p>I am building an app in Rails 4 using Cancancan for role authorization. I have an ability defined that works for individual records but not the :index action.</p>
  
  <p>I have a user role called 'RVSP'. RVSPs are assigned <code>WorkOrders</code>, from which the RVSP will create a <code>Record</code>. </p>
  
  <pre><code>class WorkOrder &lt; ActiveRecord::Base
    has_one :record
    belongs_to :rvsp, class_name: "User"
  end
  
  class Record &lt; ActiveRecord::Base
    belongs_to :work_order
  end
  </code></pre>
  
  <p>Here's my problem: I want RVSP users to be able to read or update <code>Records</code> where the <code>WorkOrder</code> was assigned to that RVSP. Here's the ability definition so far:</p>
  
  <pre><code>can [:read, :update], Record, Record.for_rvsp(user.id) do |record|
    work_order = record.work_order
    user.id == work_order.rvsp_id
  end
  </code></pre>
  
  <p>The scope <code>Record.for_rvsp</code> is this monstrosity:</p>
  
  <pre><code>scope :for_rvsp, -&gt; (rvsp_id) { where( work_order: { rvsp: { id: rvsp_id } } ) }
  </code></pre>
  
  <p>So: How do I define the ability and/or query for all <code>Records</code> where the <code>Record's</code> <code>WorkOrder's</code> <code>rvsp_id</code> matches the current user's id? I suspect it's a join of some kind but I'm new to this and haven't done that before.</p>
  
  <p>P.S. I thought of just adding a <code>created_by</code> column to <code>Record</code>, but I already have that through PaperTrail, which I'm using for an audit trail. But <code>Record.versions.first.whodunnit</code> is about the same as <code>Record.work_order.rvsp_id</code> as far as difficulty of the query is concerned. Thanks for any advice you can offer!</p>
  
  <p>P.P.S. I'm using Postgres but I'd rather not do any database-specific SQL if I can avoid it.</p>