0

次のモデルを検討してください。

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. まだ存在しない場合は、特定の医師に患者を追加します

私は、これを2つの方法で行うことができると思いました:

方法 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

さて、上記の2つの方法のうち、どちらがより良い方法でしょうか? また、パフォーマンスの点で上記の用語よりも優れている別の方法はありますか?

4

1 に答える 1

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 は不必要に冗長です。

于 2013-10-28T19:43:12.217 に答える