【问题标题】:How to reference values in a join table for a rails where method?如何为rails where方法引用连接表中的值?
【发布时间】:2013-04-23 03:28:15
【问题描述】:

这是一个菜鸟级别的问题。

我有两个模型:通过表格图表连接的患者和提供者。

我使用关联“has_many :through”而不是“has_and_belongs_to_many”,因为我需要将另一列添加到图表表 [称为patient_mrn],我知道我无法处理“has_and_belongs_to_many”场景。

患者模型具有:

    has_many :charts
    has_many :providers, :through => :charts

Provider 模型有:

  has_many :charts
  has_many :patients, :through => :charts

图表模型有:

    belongs_to :patient
    belongs_to :provider

我正在尝试在 Patient 模型上调用 where 方法来检索具有以下条件的所有患者:

-该患者的图表连接表中的 provider_id 等于给定值 [@exam.provider_id] 和

- 该患者的 Chart 连接表中的 patient_mrn 等于给定值 [@exam.patient_mrn]。

这是我想尝试的,但它显然不起作用。我会误入歧途吗?

@patient = Patient.where(:patient.chart[provider_id] => @exam.provider_id,
          :patient.chart[patient_mrn] => @exam.patient_mrn)

【问题讨论】:

    标签: ruby ruby-on-rails-3


    【解决方案1】:

    Joining tables 是您需要执行的操作,以便在模型的关联表上指定条件。 (查看specifying conditions 部分,了解您想要做什么的示例)。

    但是,简而言之,您想加入您的chart 表并在其上指定条件。您的查询应该类似于:

    @patients = Patient.joins(:charts).where(:charts => { :provider_id => @exam.provider_id, :patient_mrn => @exam.patient_mrn })  
    

    这应该返回所有Patientschart 具有给定的provider_idpatient_mrn

    【讨论】:

    • 感谢男爵- 工作得很好!!!我忘了问如何在加入的那个中再添加一个 AND 术语? Patient.find(:all, :conditions=>['dob = ?', @exam.patient_dob]) 谢谢!!!
    • 再接再厉where: Patient.joins(:charts).where(:dob => ...).where(:charts => { ... })
    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多