如何使用Scope使原始SQL查询可链接? -Rails

时间:2018-01-12 13:44:43

标签: sql ruby-on-rails ruby postgresql activerecord

我编写了一个SQL,我希望它是可链接的,或者我可以将此查询用作Rails中的作用域?有什么想法吗?

select '{Critical: '||"Critical"||', Major: '||"Major"||', Moderate: 
'||"Moderate"||', Minor: '||"Minor"||', Clear: '||"Clear"||'}' as result
from (
    select
      sum(case when max_weight=1   THEN 1 else 0 End ) as "Clear",
      sum(case when max_weight=2   THEN 1 else 0 End ) as "Minor",
      sum(case when max_weight=3   THEN 1 else 0 End ) as "Moderate",
      sum(case when max_weight=22  THEN 1 else 0 End ) as "Major",
      sum(case when max_weight=160 THEN 1 else 0 End ) as "Critical",
      count(*) as number_of_answers
    from (
      select 
        fua.forms_user_id, 
        max(fa.weight) max_weight
      from 
        public.forms_user_answers fua
        join public.forms_users fu on (fua.forms_user_id  = fu.id)
        left join public.form_answers fa on (fua.form_answer_id = fa.id)
      where 
        fu.form_id = #{form.id}
      group by 
        fua.forms_user_id
    ) subq
) subq1

1 个答案:

答案 0 :(得分:0)

您不太可能使用ActiveRecord进行可链接的查询。但是你当然可以在Rails中为查询创建一个范围:

scope :my_scope, -> {
  self.connection.execute("
    select '{Critical: '||"Critical"||', Major: '||"Major"||', Moderate: 
    '||"Moderate"||', Minor: '||"Minor"||', Clear: '||"Clear"||'}' as result
    from (
        select
          sum(case when max_weight=1   THEN 1 else 0 End ) as "Clear",
          sum(case when max_weight=2   THEN 1 else 0 End ) as "Minor",
          sum(case when max_weight=3   THEN 1 else 0 End ) as "Moderate",
          sum(case when max_weight=22  THEN 1 else 0 End ) as "Major",
          sum(case when max_weight=160 THEN 1 else 0 End ) as "Critical",
          count(*) as number_of_answers
        from (
          select 
            fua.forms_user_id, 
            max(fa.weight) max_weight
          from 
            public.forms_user_answers fua
            join public.forms_users fu on (fua.forms_user_id  = fu.id)
            left join public.form_answers fa on (fua.form_answer_id = fa.id)
          where 
            fu.form_id = #{form.id}
          group by 
            fua.forms_user_id
        ) subq
    ) subq1
  ")
}