각 고객의 마지막 날의 마지막 레코드를 통계 테이블에서 가져 오려고합니다. 마지막 날부터 가장 많이 팔린 품목을 가진 고객을 선택하고 싶습니다.모든 고객에게서 레일의 마지막 레코드를 선택하십시오
통계는 매시간 생성되므로 고객의 통계가 여러 개 있지만 마지막으로 통계가 필요합니다.
몇 가지 명령을 시도했지만 오류가 발생했습니다.
Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.order(created_at: :desc)
또는
Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.last
가 뽑은와 최고의 솔루션인가? 아니면 2 개의 선택을 만들어야합니까? 어디에서 'sold_items'를 배치해야하는지 잘 모르겠습니다.
해결 방법이 될 수도 있지만 확실하지 않습니다.
Customer.all.each do |customer|
stats = customer.statistics.where("created_at < ?",Date.today).last
count = stats.sold_items if stats.sold_items > count
best = customer if count = stats.sold_items
end
모델 : 고객 has_many : 통계 - belongs_to 통계 :
모델 선언을 추가 할 수 있습니까? 첫 번째 쿼리를 작동 시키려면 조인을해야합니다. 그래서 두 번째. – marmeladze
'Customer' 모델과'Statistic' 모델 사이에'has_many''belongs_to' 관계가 있습니까? – sa77
오른쪽. 고객 has_many : 통계 및 통계 belongs_to : 고객 –