`
bellstar
  • 浏览: 148482 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

activerecord查询joins选项使用范例

阅读更多
示例相关需求: 在处方列表中显示病人姓名(处方关联到就诊记录,就诊记录关联到病人)
class Prescription < ActiveRecord::Base
  belongs_to :patient_case_detail
 has_one :patient_case, :through => :patient_case_detail
end

Prescription.find(:first, :joins => [:patient_case_detail => :patient_case], :select => "prescriptions.*,patient_cases.patient_name")

在CONSOLE下运行返回的是Presction对象,是看不到patient_name的
#<Prescription id: 1, patient_case_detail_id: 1, subject: "桍", created_person: 2, department_id: nil, flag: 0, description: "sdfsdfASDFASDF ", created_at: "2009-12-16 08:35:00", updated_at: "2009-12-18 07:00:36">

以JSON打印出来就能看到了
Prescription.find(:first, :joins => [:patient_case_detail => :patient_case], :select => "prescriptions.*,patient_cases.patient_name").to_json

"{\"prescription\":{\"updated_at\":\"2009-12-18T15:00:36+08:00\",\"patient_case_detail_id\":1,\"subject\":\"\\u684d\",\"patient_name\":\"\\u674e\\u900d\\u9065\",\"id\":1,\"flag\":0,\"created_person\":2,\"description\":\"sdfsdfASDFASDF \",\"department_id\":null,\"created_at\":\"2009-12-16T16:35:00+08:00\"}}"


生成的SQL语句
SELECT prescriptions.*,patient_cases.patient_name FROM `prescriptions` INNER JOIN `patient_case_details` ON `patient_case_details`.id = `prescriptions`.patient_case_detail_id INNER JOIN `patient_cases` ON `patient_cases`.id = `patient_case_details`.patient_case_id ORDER BY id DESC
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics