Nilay Anand
Nilay Anand

Reputation: 340

Rails Active Record Associations: fetch data from multiple table

I have tables in db as following migration script:

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

And the model class looks like:

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

I'm able to pick all patients data of specific physician using:

patients = Physician.find(123).patients

The problem is, I need appointment_date, which is stored in appointment table, along with patient details. Somehow I'm not able to figure out how to fetch it.

Upvotes: 1

Views: 1586

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

You can join Patient and Appointment models to get the required data easily:

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

You can put the required condition in the where clause and add more attributes from the patients and appointments tables in the select clause that you want to select.

See Active Record Query Interface for more information on this.

Update

I misunderstood your question initially. Th easiet way to get what you want is pointed by midN in his answer.

Upvotes: 1

midN
midN

Reputation: 607

Relation looks completely right so querying should be quite easy or are you having some problems?

If you need appointment_date i would probably query Appointments of Physician instead:

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

Upvotes: 1

Related Questions