如何在Rails ActiveRecords中创建表名的别名

时间:2016-05-22 08:11:02

标签: sql ruby-on-rails ruby activerecord

select user_id,  max(perception_score) as max, min(perception_score) as min from temp_user_notes group by user_id as t1;    

我正在尝试在rails活动记录中转换此sql查询,但很难创建别名

2 个答案:

答案 0 :(得分:2)

只需在select方法调用中使用SQL别名功能:

TempUserNote.select('user_id, max(perception_score) as max, min(perception_score) as min').group(:user_id)

答案 1 :(得分:2)

您可以使用ActiveRecord的from方法将表别名为其他名称。

例如,您的部分查询可能是:

TempUserNote.
  select("t1.user_id, (t1.max - t1.min) as std_deviation").
  from(
    TempUserNote.
      select("user_id, max(perception_score) as max, min(perception_score) as min").
      group(:user_id),
    :t1
  )