开发者

Rails Rich Association - Overwriting to association model

Suppose we have three models PATIENTS, NURSES, and their association model APPOINTMENTS.

This week all patients have to meet with their nurses.

A patient has many nurses, and a nurse has many patients. Likewise, a patient has many appointments, but only one per nurse, and a nurse has many appointments, but only one per patient.

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

Obviously, the APPOINTMENT belongs to both the patient and the nurse.

However, I also want a way for the nurse to be able to tick off whether or not the patient showed up. I implemented this within the migration like such:

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

end

In the console, I could create an instance of everything, and could do the following:

appt = Appointment.new
patient = Patient.new
nurse = Nurse.new

patient.appointments << appt
nurse.appointments << appt

Now, here comes the question: How do I implement it so that the Nurse in that appointment is able to edit the value of the boolean to TRUE? So far, I can change the value of the instance of the appointment by typing:

appt.present = true

But this not what I want. I want the nurse to be able to modify this association, and lock out the patient from changing anything.

Should I simply not be using rich associations f开发者_如何学Goor this?


I'm assuming your question is about how to use these associations. You can recall and modify the appointment record after the appointment is kept, like so:

# current_nurse is the nurse using the system and reporting
appt = current_nurse.appointments.where(:patient_id => params[:patient_id]).first
appt.update_attribute :present, true

To prevent the patient from accessing and modifying the appointment, you would need an authentication mechanism, such as devise. Then only grant Nurses permission to access the system.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜