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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值