Question: Access data with through option on models

Question

Access data with through option on models

Answers 2
Added at 2017-01-01 11:01
Tags
Question

"Hi guys!" I'm currently working with a project on Rails. I have three tables.

class CreateDoctors < ActiveRecord::Migration
  def change
    create_table :doctors do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

    class CreatePatients < ActiveRecord::Migration
  def change
    create_table :patients do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

    class CreateAppointments < ActiveRecord::Migration
  def change
    create_table :appointments do |t|
      t.date :date_appointment
      t.references :doctor, index: true, foreign_key: true
      t.references :patient, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

I have been able to insert data in the table called appointment and access data from other tables thanks to the foreign keys. what I want to do now is to access data from the table "doctors" to "patients" and vice-versa. for example; I want to know how many Patients, "X" Doctor has. Is possible to do this?

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

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

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

Thank you!

Answers
nr: #1 dodano: 2017-01-01 11:01

Have you tried something like this?

Doctor.first.patients
Doctor.find(1).patients
Doctor.find_by(name: "aaron").patients
Patient.first.doctors
Patient.find(1).doctors
Patient.find_by(name: "dhh").doctors

Those are just some examples.

nr: #2 dodano: 2017-01-01 11:01

for example; I want to know how many Patients, "X" Doctor has:

doctor = Doctor.find_by(name: 'X')
doctor.patients.count
#=> number of patients of doctor with the name 'X'

I advise to read about ActiveRecord querying in the Rails guide.

Source Show
◀ Wstecz