我正在尝试收集一些发票,这些发票不属于尚未完成的借记卡。
因此,对于每张发票,不存在未完成的借记 因此,没有借方的发票或只有完成的借方的发票都是有效的
Invoice通过联合模型InvoiceDebit
与借方有一个has_many关系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 :(得分: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