2013-12-10 1 views
1

아직 완료되지 않은 직불 카드의 일부가 아닌 청구서 모음을 얻으려고합니다.레일 연결 : NOT EXIST

그래서 각 인보이스에는 직불는 그래서 을 완료되지 중 하나를 완료하는 경우에만 직불 결제와 NO 직불 결제 또는 청구서와 송장

송장 모델 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 

이미 AREL을 사용하여 현재 로그인 한 사용자에 대해서만 인보이스 풀을 제한하므로 SQL에서 전체 쿼리를 작성하지 않는 것이 좋습니다.

+0

그래서 당신은 거짓 완료 값으로 직불가 존재하지 않는 모든 송장을 원하는? –

+0

그것이 내가 OP의 진술을 읽는 방법이다. 동등하게, 존재하는 모든 빚이 진실한 모든 청구서. – Chowlett

+0

DebitInvoice에 올바른 'foreign_keys'설정이 있습니까? (IE'invoice_id' 및'debit_id'? –

답변

1

효율적인 SQL 구문으로 where 절을 구성 할 수 있습니다.

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 % 레일이 아닌 잠재적으로 덜 효율적입니다. –