-3.1 연습 :최저 레일을 감안할 때 복잡한 쿼리
(모델) : 예를 들어
Contract (has_many :invoices, belongs_to :user)
Invoice (belongs_to :contract)
이 방법 :이 경우
my_contracts = Contract.where(user_id: current_user.id) #=> [#<Contract id: 1, title: "1">, #<Contract id: 2, title: "2">]
우리는 사용자에 대한 두 가지 계약이있다. 각 계약서에는 여러 개의 송장이 있습니다.
이제 계약서별로 모든 인보이스를 수집하고 'updated_at'별로 정렬해야합니다. 다음과 같음 :
all_invoices = my_contracts.map{|i| i.invoices.sort_by(&:updated_at)}
그러나 ActiveRecord를 사용합니다.
어떻게 제대로 할 수 있습니까?
Invoice.joins(:contracts).where(user_id: current_user.id).order(:updated_at)
Arel 같은
확실하지 않은 볼 수 있지만 '계약 및 송장 테이블에 있기 때문에 updated_at에 모호한 오류가 발생할 수 있습니까? '.order ("invoices.updated_at")'가 필요할 수도 있습니다. – house9
사실입니다. 'Invoice.joins (: contracts) .where (user_id : current_user.id) .order (: updated_at) .to_sql'을 사용하여 레일스 콘솔에서 이것을 시도해보고 생성 된 SQL을 확인하는 것이 가장 좋습니다. (그리고 자연스럽게 모든 것을 검사하는 테스트 케이스가 있어야한다 ;-)) –