创建WaitlistMember时要求父Contact的name属性非空该如何实现
实现方案
以下两种方案都不会影响Contact单独创建时允许name为空的原有逻辑,仅在创建WaitlistMember时触发关联Contact的name非空校验:
方案1:在WaitlistMember侧加自定义关联校验(最通用,无需修改Contact原有逻辑)
适合仅在WaitlistMember场景下需要校验Contact name的场景,侵入性最低:
class WaitlistMember < ApplicationRecord belongs_to :contact # 新增自定义校验规则 validate :contact_name_must_present private def contact_name_must_present if contact.blank? || contact.name.blank? errors.add(:contact, "关联的联系人姓名不能为空") end end end
该方案对新建关联Contact、绑定已有Contact两种场景都生效。
方案2:使用Rails上下文校验(适合多场景复用校验规则)
如果后续还有其他业务场景需要校验Contact name非空,可以用上下文校验避免重复编码:
- 首先给Contact加带上下文的校验规则
class Contact < ApplicationRecord has_many :waitlist_members # 仅在:for_waitlist这个自定义上下文下才校验name非空 validates :name, presence: true, on: :for_waitlist end
- 然后在WaitlistMember中触发对应上下文的校验
class WaitlistMember < ApplicationRecord belongs_to :contact validate :check_contact_valid_for_waitlist private def check_contact_valid_for_waitlist return if contact&.valid?(:for_waitlist) # 把Contact的报错合并到当前对象,方便前端统一展示 contact&.errors&.each do |attr, msg| errors.add("contact.#{attr}", msg) end end end
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

