如果尚未在rails 4中预约,则将患者添加到Physician模型

时间:2013-10-28 19:04:38

标签: ruby-on-rails activerecord ruby-on-rails-4 rails-activerecord

考虑以下模型:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

目标

  1. 创建患者(如果尚未存在)。
  2. 将患者添加到特定医生(如果尚未存在)
  3. 我想,我可以通过两种方式做到这一点:

    方法1

    physician = Physician.find(physician_id)
    unless Patient.where(email: email).empty?
      record = physician.patients.create email: email
    else
    #Patient already exist, just add them to appointment
      record = Patient.where(email: email)
      physician.patients << record
    end
    

    方法2

    physician = Physician.find(physician_id)
    record = Patient.find_or_create_by(email: email)
    # avoid overhead of SQL JOINS, use simple SELECT/CREATE
    if Appointment.where(physician_id: physician_id).where(patient_id: record.id).empty?
       Appointment.create physician_id: physician.id, patient_id: record.id
    end
    

    现在, 哪个是上述两个更好的方法?另外,在性能方面还有另一种比上述术语更好的方法吗?

1 个答案:

答案 0 :(得分:1)

选项3如何:

physician = Physician.find(physician_id)
unless physician.patients.where(email: email).exists?
  patient = Patient.find_or_create_by(email: email)
  physician.appointments.create(patient: patient)
end

如果患者已经与该医生预约,这将避免对find_or_create_by进行不必要的呼叫。

对于记录,调用model.association.create(...)将不会执行任何加入。它适用于表示关联的ActiveRelation对象,并且只会触发INSERT语句。但是,您建议的方法1还存在其他一些技术问题,而您的方法2也是不必要的冗长。