考虑以下模型:
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
目标:
- 如果不存在,则创建一个患者。
- 将患者添加到特定医生(如果尚不存在)
我想,我可以通过两种方式做到这一点:
方法一
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
方法二
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
现在,哪一个是上述两个更好的方法?另外,在性能方面是否有另一种比上述术语更好的方法?