2017-01-01 2 views
0

「こんにちは!私は現在、Railsに関するプロジェクトに取り組んでいます。私は3つのテーブルを持っています。モデルのthroughオプションを使用してデータにアクセスする

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 

私は、予定と呼ばれるテーブルにデータを挿入し、外部キーのおかげで他のテーブルからデータにアクセスすることができました。私が今したいのは、テーブル "医師"から "患者"にデータをアクセスし、その逆にすることです。例えば;私はどれくらいの患者がいるのか知りたいのですが、 "X" Doctorが持っています。これを行うことは可能ですか?

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 

ありがとうございます!

答えて

1

あなたはこれを試しましたか?

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 

これはほんの一例です。

+0

Doctor.find_by(名前: "aaron")。patients <----これがトリックでした!ありがとうございました! –

1

例えば、私はおよそActiveRecord querying Railsのガイドのを読むことをお勧めし

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

:私はどのように多くの患者さん、「X」医者が持っているかを知りたいです。

+0

あなたは私が実際にその記事を読んでいたことを知っています。そしてあなたのコメントで私はそのコンセプトを理解することができました。大変ありがとうございます! –

関連する問題