簡體   English   中英

rails-在通過模型填充之前檢查

[英]rails - check before populating through model

我有醫師和患者兩個模型,如下所示:

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

p =患者的目標。

因此,p.appointments.append(physican_obj)是正確的方法。 但是,如果我兩次運行相同的命令,它將兩次添加相同的內容。 因此,在追加之前檢查它是否已經存在,這是否很好? 最好的方法是什么?

我的要求是,獲得要添加的對象列表,因此需要遍歷每個對象並追加每個對象。 如果需要在添加之前進行檢查,則需要在每個循環中進行檢查,這是一個昂貴的過程。

一種方法是使用范圍。

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

  validate_uniqueness_of :physician_id, scope: :patient_id
end

這將確保不允許同時復制兩個ID的記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM