Validating Child Objects against Parent

Ajaya Agrawalla wrote:

This is my situation. I have a form where I create a Parent Object and Two Child object. This is all in one form. In my Controller create.. I need to do validation on all three(parent and 2 child).

But my child object needs validate a attribute against a attribute of the parent. To summarize..

Parent{:age => 50} child {:age => 10}

In child validation a like to say def validate   if self.age > self.parent.age     # errror   end end

But the problem is the parent is new and not in the database yet. So the question is how can I pass a object to the child's validation. I would like to say something like child.valid?(parent)

Just set child.parent to the parent object, even if the parent object is new. This is normally done in the controller as

   @child = @parent.build_child(params[:child])

which is equivalent to

   @child = Child.new(params[:child])    @child.parent = @parent

Well.. Seems like this doesn't work.

@p = Parent.new(params[:parent]) @c = @p.childs.build(params[:child])

@c.parent is set to nil and I see that @c.parent_id is set 1 even id @p is new.

The @p.build_child method not there..

Any idea what I am doing wrong?

AJ

AJAY A wrote:

Well.. Seems like this doesn't work.

@p = Parent.new(params[:parent]) @c = @p.childs.build(params[:child])

@c.parent is set to nil and I see that @c.parent_id is set 1 even id @p is new.

Is params[:child][:parent_id] set?

In any case, looking at the core source I see that build does not in fact assign a new parent. You have to use the explicit method I posted:

@child = Child.new(params[:child]) @child.parent = @parent

The @p.build_child method not there..

Yes, that's for has_one. You have a has_many.

params[:child][:parent_id] is not known until the record is saved.

Anyway.. I would use the explicit method.

Thanks for the help

AJ