2009-06-10 2 views
0

프로젝트는 3 개의 테이블을 가지고 있습니다 : 클라이언트, 송장, 배달레일을 사용하여 3 개의 테이블에서이 결과를 찾는 방법?

관계는 다음과 같습니다 :

    client has_many invoices 
      client has_many deliveries 


       invoices belongs_to client 
       deliveries belongs_to client 

두 송장과 배달 모델 모두 날짜 필드가 있습니다.

이제 해당 달의 송장 또는 배달 중 최소 하나의 레코드를 보유한 모든 고객을 찾고 싶습니다. 따라서 인보이스에 레코드가 있거나 배달 또는 심지어 둘 다에 레코드가있는 개별 클라이언트가 필요합니다.

Rails 또는 SQL을 사용하여 클라이언트를 찾는 방법은 무엇입니까?

도움 주셔서 감사합니다

답변

1

이것은 나의 첫번째 균열 것 : 내가

class Client < ActiveRecord::Base 
    named_scope :active_since, lambda {|date| {:include => [:deliveries, :invoices], :conditions => ['(deliveries.date > :start_date) OR (invoices.date > :start_date)', :start_date => date]}} 

    # or 
    def self.find_by_delivery_or_invoice_activity 
    all(:include => [:deliveries, :invoices], :conditions => ['(deliveries.date > :start_date) OR (invoices.date > :start_date)', :start_date => 1.month.ago]) 
    end 
end 

:

Client.all(:include => [:deliveries, :invoices], :conditions => ['(deliveries.date > :start_date) OR (invoices.date > :start_date)', :start_date => 1.month.ago]) 

가 이상적으로는이 문제를 처리하기 위해 모델에 named_scope 또는 사용자 찾기 방법을 사용할 것 꽤 이것은 네가 뭘 가까이에 꽤 있어야한다. eed, 그러나 나는 당신의 상황에 대한 약간의 수정 없이는 작동하지 않을 것이라고 생각합니다.

2

Client.find(:all).collect { |c| c if c.has_invoice_in_month(y,x) or 
c.has_delivery_in_month(y,x))}.uniq 

uniq 전화뿐만 아니라

을 반환받을 모든 전무 개체를 제거합니다

많은 ahve 송장 또는 배달 중 일부 클라이언트 만 Client.find (: all, : join => : invoices) + Client.find (: all, : join = : 배달)

관련 문제