2013-12-10 42 views
1

我想获得发票的集合,这是不是尚未完成的借记的一部分。Rails协会:通过不存在

所以每个发票没有付款必须存在未完成 因此,无论与被完成NO借方或发票,只有借记发票是有效

发票具有的has_many关系借记通过加盟模式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 

我宁愿不写出SQL中的整个查询,因为我已经使用AREL来限制只有当前登录用户的发票池。

+0

所以,你要对此有不完成的值是假的存在借记所有发票? –

+0

这就是我阅读OP的声明的方式。同样,所有确实存在的借记都已经完成的发票。 – Chowlett

+0

您是否在DebitInvoice中设置了正确的'foreign_keys'? (IE'invoice_id'和'debit_id'? –

回答

1

您可以构造一个有效的where子句作为SQL片段。

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 

然后:

Invoices.for_current_user(current_usser.id).does_not_have_an_incomplete_debit.all 
+0

不是真正的铁杆方式做事,但我担心这是不可能的,我会测试它并接受你的答案 – ChrisDekker

+0

你可以用外连接方法获得更多的railsie,但是它可能效率较低,而且不是100%的导轨。 –