【问题标题】:Rails Active Record Associations: fetch data from multiple tableRails Active Record 关联:从多个表中获取数据
【发布时间】:2023-03-15 22:30:01
【问题描述】:

我在 db 中有如下迁移脚本的表:

class CreateAppointments < ActiveRecord::Migration
  def change
    create_table :physicians do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :patients do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :appointments do |t|
      t.belongs_to :physician, index: true
      t.belongs_to :patient, index: true
      t.datetime :appointment_date
      t.timestamps null: false
    end
  end
end

模型类看起来像:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

我可以使用以下方法选择特定医生的所有患者数据:

patients = Physician.find(123).patients

问题是,我需要存储在约会表中的约会日期以及患者详细信息。不知何故,我无法弄清楚如何获取它。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord


    【解决方案1】:

    关系看起来完全正确,所以查询应该很容易,还是您遇到了一些问题?

    如果您需要约会日期,我可能会改为查询 Appointments of Physician:

    Physician.find_by(id: 123).appointments.each do |x|
      print "Date: #{x.appointment_date}\n"
      print "Patient: #{x.patient.name}"
    end
    

    【讨论】:

      【解决方案2】:

      您可以通过joinPatientAppointment模型轻松获取所需数据:

      Patient.joins(:appointments).where(. . . ).select('appointments.appointment_date')
      

      您可以将所需条件放在where 子句中,并在您要选择的select 子句中添加patientsappointments 表中的更多属性。

      有关更多信息,请参阅Active Record Query Interface

      更新

      我最初误解了你的问题。 midN 在他的回答中指出了获得您想要的东西的最简单方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 2023-03-21
        • 2017-10-14
        • 2012-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多