Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validates_associated model with condition

I have the following validates_associated scenario

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

when i create a parent, either of son or daughter is only created not both. Now my problem is, when i try to create parent with son, then validation fails due to daughter validation and vice versa.

Is there any way that i can validate only son when son parameters are posted or or validate only daughter when daughter parameters are posted

Thanks

like image 844
Gagan Avatar asked May 09 '26 06:05

Gagan


1 Answers

You can supply an :if option and test if the associated 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
like image 92
Netzpirat Avatar answered May 10 '26 19:05

Netzpirat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!