「こんにちは!私は現在、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
ありがとうございます!
Doctor.find_by(名前: "aaron")。patients <----これがトリックでした!ありがとうございました! –