Question

I am trying to get a collection of Invoices which are NOT part of a Debit that is not yet completed.

So for each invoice no debit must exist that is not completed So either invoices with NO debits or invoices with only debits that are completed are valid

Invoice has a has_many relation to Debit through a join model InvoiceDebit

class Invoice < ActiveRecord::Base
   has_many :debit_invoices
   has_many :debits, :through => :debit_invoices
end

class DebitInvoice < ActiveRecord::Base
   belongs_to :invoice
   belongs_to :debit
end

class Debit < ActiveRecord::Base
   attr_accessible :completed

   has_many :debit_invoices
   has_many :invoices, :through => :debit_invoices
end

I would prefer to not write out the entire query in SQL, as I already use AREL to constrain the pool of invoices for only the current logged in user.

Was it helpful?

Solution

You can construct an efficient where clause as a SQL fragment.

def does_not_have_an_incomplete_debit
  self.where("not exists
               (select null
                  from debit_invoices di
                  join debits         d on d.id = di.debit_id
                 where di.invoice_id = invoices.id and
                       d.completed   = false)")
end

Then:

Invoices.for_current_user(current_usser.id).does_not_have_an_incomplete_debit.all
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top