首页 > 解决方案 > Rails 5:仅当该 id 没有填充的特定字段时才插入/更新

问题描述

我有一个Followups包含字段的表:patient_iddeath_date(和其他字段..)。

可能有多个相同的记录,patient_id但必须只有death_date一个patient_id。唯一索引不起作用,因为用户可以插入两个不同的死亡日期。

在 Rails 5 中实现这一目标的最佳方法是什么?

如果可能,请举个例子。

谢谢

标签: validationruby-on-rails-5

解决方案


您可以通过模型上的回调来做到这一点Followup:假设Patient has_many :followups

class Followup
  belongs_to :patient
  validate :check_for_existing_death_date

  private

  def check_for_existing_death_date
    # This will grab the first one if any with a death date exist
    # This also assumes that the patient_id and patient exist
    followup = patient.followups.where("death_date IS NOT NULL").take

    # if you want to raise an error...
    if followup
      errors.add(:death_date, 'There is already a death date for this patient')
      return false
    end

    # If not, do something with the data
    # if followup
    #   self.death_date = nil # or followup.death_date if you want it saved on followups as well
    # end
  end
end

我认为最好的方法是将其存储death_datePatient记录中,因为每个患者只发生一次死亡。


推荐阅读