validates_associated model with condition
I have 开发者_Go百科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
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
Why don't you use an associated child object, which has an attribute (i.e. gender
) if it's beeing a son or a daughter.
Child
model (male or female, depending on value in 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
will be Embedded in Parent
model:
class Parent
include Mongoid::Document
embeds_one :child
validates_associated :child
end
精彩评论