Validating Child Objects against Parent

Folks,

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)

I am using hack right now to have a method on the child object and doing
that. Is there more of a standard way to pass a object rails validation
methods?

AJ

Ajaya A. wrote:

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


We develop, watch us RoR, in numbers too big to ignore.

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

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

Anyway… I would use the explicit method.

Thanks for the help

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.


We develop, watch us RoR, in numbers too big to ignore.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs