2011-08-10 171 views
1

我的最後一個職位是在寫一個SQL查詢與一個LEFT OUTER條件最好的方式加盟:
LEFT OUTER JOIN with conditions (where, order by)?如何將SQL查詢轉換爲Rails活動記錄查詢?

現在,我需要的是好片的SQL轉換成甜蜜的Active Record查詢(Rails 3的)。 ;-)

我有2種型號:

培訓的has_many:training_histories

TrainingHistory belongs_to的:訓練

我如何寫一個範圍,得到的結果下面的SQL檢索?

SELECT tc.id, tc.name, tc.order, 
th.id as history_id, th.finished_at, th.score 
FROM trainings tc 
LEFT OUTER JOIN training_histories th ON th.training_id = tc.id 
    and th.id = 
    (SELECT th1.id from training_histories th1 where th1.training_id = tc.id 
    and th1.finished_at is not null 
    order by th1.finished_at desc limit 1) 
WHERE tc.id > 4 
AND tc.id < 8 
GROUP BY tc.id 
ORDER BY tc.order_by ASC, tc.id ASC 

我想檢索培訓的所有記錄,並添加TRAINING_HISTORIES的有關最後一個有效(又名完)記錄。

有什麼建議嗎?

謝謝

+0

爲什麼不做2選擇請求? –

+0

並在紅寶石合併數據? ;-) –

回答

7

鋼軌3,試試這個:

Training.select("trainings.id, trainings.name, trainings.order, 
       trainings.id AS history_id, training_histories.finished_at, 
       training_histories.score"). 
     joins("LEFT OUTER JOIN training_histories 
       ON training_histories.training_id = trainings.id 
       AND training_histories.id = (SELECT th1.id FROM training_histories th1   
              WHERE th1.training_id = tc.id 
              AND th1.finished_at IS NOT NULL 
              ORDER BY th1.finished_at DESC LIMIT 1)"). 
     where("trainings.id > 4 AND trainings.id < 8"). 
     group("trainings.id"). 
     order("trainings.order_by ASC, trainings.id ASC") 

基本上,你只是轉換您預先寫好的查詢到Rails 3 finder方法。