简体   繁体   English

验证引用同一张表的同一张表中的两个外键

[英]validate two foreign keys in the same table referencing the same table

I have two fields, user_id and assignee_id , in my table cards. 我的桌卡中有两个字段user_idassignee_id They are both referencing a user in my table users. 他们都在我的表用户中引用一个用户。 The presence of the first one is required, but not the second one. 需要第一个,但第二个不是。

In my validation, I want to check the integrity and the presence of the first, and only the integrity of the second, if filled. 在验证中,我想检查第一个的完整性和存在性,如果已填充,则仅检查第二个的完整性。

I have tried that, but it doesn't work : 我已经尝试过了,但是没有用:

  belongs_to :user
  belongs_to :assignee, :class_name => 'User', :foreign_key => :assignee_id

  validates_presence_of [:title, :user_id]
  validates :user, presence: true
  validates :assignee_id

Does anyone know how to do it properly please ? 有人知道如何正确地做吗? Thank you in advance. 先感谢您。

In this case you would usually create a custom validation using ActiveRecord::Validations# validate . 在这种情况下,您通常会使用ActiveRecord :: Validations# validate创建自定义验证。

validates :user_id, presence: true
validate  :integrity_of_assignee_id, if: ->(obj) { obj.assignee_id.present? }

private

def integrity_of_assignee_id    
  # Add error to the field if the `assignee_id` is invalid
  errors.add(:assignee_id, 'Not valid assignee_id') unless User.find_by(id: assignee_id)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM