3つのモデルPATIENTS、NURSES、およびそれらの関連モデルAPPOINTMENTSがあるとします。
今週、すべての患者は看護師と会う必要があります。
患者には多くの看護師がいて、看護師には多くの患者がいます。同様に、患者には多くの予定がありますが、看護師ごとに1つだけであり、看護師には多くの予定がありますが、患者ごとに1つだけです。
class Patient < ActiveRecord::Base
has_many :appointments
has_many :nurses, :through => :appointments
end
class Nurse < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :patient
belongs_to :nurse
end
明らかに、予定は患者と看護師の両方に属しています。
しかし、私はまた、患者が現れたかどうかにかかわらず、看護師がチェックできる方法を望んでいます。私はこれを次のように移行内に実装しました。
class CreateAppointments < ActiveRecord::Migration
def self.up
create_table :appointments do |t|
t.references :patient
t.references :nurse
t.boolean "present", :default => false
t.timestamps
end
add_index :job_enrollments, ['patient_id', 'nurse_id']
end
def self.down
drop_table :appointments
end
終わり
コンソールでは、すべてのインスタンスを作成でき、次のことができます。
appt = Appointment.new
patient = Patient.new
nurse = Nurse.new
patient.appointments << appt
nurse.appointments << appt
ここで、質問があります。その予定のナースがブール値をTRUEに編集できるようにするには、どうすれば実装できますか?これまでのところ、次のように入力して、予定のインスタンスの値を変更できます。
appt.present = true
しかし、これは私が望むものではありません。看護師がこの関連付けを変更し、患者が何も変更しないようにロックアウトできるようにしたいと思います。
これにリッチアソシエーションを使用するべきではありませんか?