validation - Rails 5:仅当该 id 没有填充的特定字段时才插入/更新
问题描述
我有一个Followups
包含字段的表:patient_id
,death_date
(和其他字段..)。
可能有多个相同的记录,patient_id
但必须只有death_date
一个patient_id
。唯一索引不起作用,因为用户可以插入两个不同的死亡日期。
在 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_date
在Patient
记录中,因为每个患者只发生一次死亡。
推荐阅读
- windows - 在 Firemonkey 中更改 Windows 标题栏颜色
- laravel - EC2 实例连接到可通过 VPN 访问的 RDS
- java - 如何检查字符串列表是否包含确切的字符串?
- javascript - 如何从嵌入在脚本标签中的外部 javascript 文件中获取名称、纬度和经度信息?
- javascript - React + Redux - 状态问题
- html - Angular,如何在一页上显示多个随机报价?
- java - JPA:使用带有规范的findAll时如何按字段自定义顺序排序
- salesforce - 字符串结尾的 Salesforce 公式
- embedded - AUTOSAR DEM 中的老化和修复有什么区别?
- c - 无法弄清楚如何检查 C 代码中的值