Vincent Déhaye Vincent Déhaye - 2 months ago 9
MySQL Question

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. 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.

Answer

In this case you would usually create a custom validation using 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
Comments