2011-07-12 93 views
4

假設我們有三個模型患者,護士和他們的關聯模型APPOINTMENTS。Rails Rich Association - 覆蓋到關聯模型

本週所有患者都必須與他們的護士見面。

患者有許多護士,護士有許多患者。同樣,患者有許多預約,但每位護士只有一位,護士有許多預約,但每位患者只有一位。

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 

但是,這不是我想要的。我希望護士能夠修改這種關聯,並鎖定患者改變任何事情。

我應該不使用豐富的協會呢?

回答

2

我假設你的問題是關於如何使用這些關聯。你可以調用和修改約會記錄預約保持後,像這樣:

# 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 

爲了防止患者訪問和修改約會,那麼你需要一個認證機制,如devise。然後只授予護士訪問系統的權限。