通过rails中的关系覆盖has_many的getter和setter

时间:2017-06-07 23:37:04

标签: ruby-on-rails activerecord model-associations

我有以下型号:

class Doctor
   has_many :doctors_appointments
   has_many :appointments, through: :doctors_appointments
   ...

   def set_appointments(appointment_list=[])
       #logic to add appointments, including defaults when list is empty
       final_appointment_list.each do
           self.appointments.append(appointment)
       end
       self.save
   end

   def get_appointments(appointment_list=[])
       if self.appointments.blank?
           self.set_appointments
       end
       self.appointments
   end
end

class Appointment
   belongs_to :doctor
   ...
end

class DoctorsAppointment
   belongs_to :doctor
   belongs_to :appointment
   ...
end

我希望能够致电

doctor.appointments = [<appointments>]

doctor_appointments = doctor.appointments

并执行我的自定义getter和setter。具体到我的问题是我如何在self.appointments.append和getter self.appointments中的setter中调用super。任何建议将不胜感激。

编辑:如果我创建了一名新医生,那么覆盖默认的getter和setter的理由就是如此。目前我要致电:

doctor = doctor.new(doctor_params)
doctor.set_appointments(appointement_params)
doctor.save

显然,医生和约会的抽象仅适用于这个问题,但在实际使用案例中,我希望能够致电

doctor = doctor.new(doctor_params)
doctor.save

其中约会是医生参数的关键,并且在保存时调用了set_appointments。

0 个答案:

没有答案