Validates_associated model with condition

I have the following validates_associated script

class Parent
  include Mongoid::Document
  validates_associated :son
  validates_associated :daughter
end

when I create a parent, either the son or daughter is not created at the same time. Now my problem is that when I try to create a parent with a son, then the check fails due to the check of the children and vice versa.

Is there a way so that I can only check the son when the parameters of the sons are sent, or or only check the daughter when the child parameters are published.

thank

+3
source share
2 answers

You can specify the: if option and check if the corresponding document exists:

class Parent
  include Mongoid::Document
  validates_associated :son, :if => Proc.new { |p| p.son.present? } 
  validates_associated :daughter, :if => Proc.new { |p| p.daughter.present? }
end
+4
source

, (.. gender), .

Child ( , gender):

class Child
  include Mongoid::Document
  field :gender, :type => Symbol
  # and more fields as you probably want
  embedded_in :parent, :inverse_of => :child
  # your validation code

  def son?
    gender == :male
  end
  def daughter?
    gender == :female
  end
end

Parent:

class Parent
  include Mongoid::Document
  embeds_one :child
  validates_associated :child
end
+3

Source: https://habr.com/ru/post/1759121/


All Articles