3

我有以下 validates_associated 场景

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

当我创建父母时,只创建儿子或女儿中的任何一个,而不是两者。现在我的问题是,当我尝试用儿子创建父母时,由于女儿验证而验证失败,反之亦然。

有什么方法可以在发布儿子参数时仅验证儿子,或者在发布女儿参数时仅验证女儿

谢谢

4

2 回答 2

4

您可以提供一个 :if 选项并测试相关文档是否存在:

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
于 2010-11-02T21:05:23.997 回答
3

你为什么不使用关联的子对象,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
于 2010-08-11T12:51:54.263 回答