这个问题与以下内容完全相同:
有没有办法使用find_by_sql搜索?
我有这个:
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")
我建议避免使用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
。这应该允许将搜索结果链接到响应,如下所示:
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