简体   繁体   English

如何将 SQL 查询转换为 Rails 活动记录查询?

[英]How to Convert SQL Query to Rails Active Record Query?

My last post was on the best way to write a SQL query with conditions on a LEFT OUTER JOIN:我的上一篇文章是关于编写带有左外连接条件的 SQL 查询的最佳方法:
LEFT OUTER JOIN with conditions (where, order by)? 带有条件的 LEFT OUTER JOIN (where, order by)?

Now, I need to convert that good piece of SQL into a sweet Active Record Query (Rails 3).现在,我需要将 SQL 的那段好片段转换为一个甜蜜的 Active Record 查询(Rails 3)。 ;-) ;-)

I have 2 Models:我有 2 个模型:

Training has_many:training_histories培训has_many:training_histories

TrainingHistory belongs_to:training TrainingHistory属于_to:training

How can I write a scope to get the results the SQL below retrieve?如何编写 scope 以获取下面的 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

I want to retrieve all the records of TRAININGS and add the last valid (aka finished) associated record of TRAINING_HISTORIES.我想检索 TRAININGS 的所有记录并添加 TRAINING_HISTORIES 的最后一个有效(又名完成)关联记录。

Any suggestions?有什么建议么?

Thank you谢谢

For rails 3, try this:对于 rails 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")

Basically, you're just converting your pre-written query into Rails 3 finder methods.基本上,您只是将预先编写的查询转换为 Rails 3 finder 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM