1
私の最後のポストは、JOINをLEFT OUTER上の条件付きのSQLクエリを記述するための最良の方法だった:
今 LEFT OUTER JOIN with conditions (where, order by)?SQLクエリをRailsのアクティブレコードクエリに変換する方法?
を、私は甘いアクティブレコードクエリ(Railsの3にSQLの良い作品を変換する必要があります)。 ;-)
私は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の最後の有効な(別名終了)に関連するレコードを追加します。
提案がありますか?
あなたがレール3の場合
なぜ2つの選択要求をしていませんか? –
ルビーのデータをマージしますか? ;-) –