Ransack和find_by_sql

时间:2019-03-19 16:12:27

标签: ruby-on-rails ransack

是否可以在find_by_sql中使用ransack?

我有这个:

def index
  @p = Patient.ransack(params[:q])
  @patients = @p.result.page(params[:page])

end

但我需要:

  @p = Patient.find_by_sql(
    "SELECT DISTINCT first_name, last_name, gender,  MAX(S.surgery_date)
     FROM patients P
     LEFT JOIN
     hospitalizations H
     ON
     P.id = H.patient_id
     LEFT JOIN
     surgeries S
     ON
     S.hospitalization_id = H.id
     GROUP BY first_name, last_name, gender")

1 个答案:

答案 0 :(得分:1)

我建议您避免使用find_by_sql并将查询转换为更真实的ActiveRecord查询

Rails 5 + 中,您可以尝试以下操作:

class Patient < ApplicationRecord
   scope :basic_info, -> { 
        self.left_joins(hospitalizations: :surgery)
           .distinct
           .select("first_name, 
                    last_name, 
                    gender,  
                    MAX(surgeries.surgery_date) as most_recent_surgery")
           .group("first_name, last_name, gender")
   }
end

这将提供与您的find_by_sql相同的SQL,但将返回ActiveRecord::Relation而不是ActiveRecord::Result。这样应该可以将ransack链接到响应,如下所示:

def index
  @p = Patient.basic_info.ransack(params[:q])
  @patients = @p.result.page(params[:page])

end

如果您使用的是 Rails小于5 ,则它会变得更加混乱,但以下内容仍会提供相同的

class Patient < ApplicationRecord
   scope :basic_info, -> { 
        patient_table = Patient.arel_table
        hospitalizations_table = Hospitaliztion.arel_table
        surgeries_table = Surgery.arel_table
        patient_join = patient_table.join(hospitalizations_table,Arel::Nodes::OuterJoin).on(
            hospitalizations_table[:patient_id].eq(patient_table[:id])
        ).join(surgeries_table, Arel::Nodes::OuterJoin).on(
          surgeries_table[:hospitalization_id].eq(hospitalizations_table[:id])
        )  
        self.joins(patient_join.join_sources)
           .select("first_name, 
                    last_name, 
                    gender,  
                    MAX(surgeries.surgery_date) as most_recent_surgery")
           .group("first_name, last_name, gender")
   }
end