views:

50

answers:

2

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

+2  A: 

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
jigfox
Actually this dosen't solve my problem.Cant we validate the assocaited model if the fields from that model is supplied?Thanks
Gagan
Sorry, but now I don't understand what's your problem here? Why doesn't this solve your problem? What's wrong with this solution?
jigfox
probably i think i didn't get what you are trying to say.A further more explanation might help.Some structured rails code will be much better.Thanks
Gagan
I've updated my answer
jigfox