# How to validate presence of children?

**URL:** <https://www.ruby-forum.com/t/how-to-validate-presence-of-children/130243>\
**Category:** Rails\
**Created:** [February 26, 2008, 6:43pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-children/130243 "2008-02-26T18:43:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![samckayak](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/58f4c7/32.png) [@samckayak](https://www.ruby-forum.com/u/samckayak)\
**Post date:** [February 26, 2008, 6:43pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-children/130243/1 "2008-02-26T18:43:12Z")

</div>

What is the best way to require the presence of a has\_one child or set  
constraints on the number of has\_many children? The only thing I’ve  
been able to come up with is to manually make my transaction, eg:

def create  
@parent = Parent.new(params[:parent])  
begin  
Parent.transaction do  
@parent.save  
@parent.build\_child(params[:child]).save!  
end  
rescue Exception =\> e  
# blah blah blah  
end  
end

Of course it is a bit more complicated for a has\_many relationship  
especially if you are using a variable number of form inputs which can  
be zero, but you get the point.

Is there a better way? I don’t mean refactoring the above code although  
perhaps something like

def create  
@parent = Parent.new(params[:parent])  
Parent.transaction do  
@parent.save  
raise ActiveRecord::Rollback unless  
@parent.build\_child(params[:child]).save  
end  
end

would be better but the point is that I would like to take this out of  
the controller altogether.

---

<div class="post-metadata">

**Author:** ![samckayak](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/58f4c7/32.png) [@samckayak](https://www.ruby-forum.com/u/samckayak)\
**Post date:** [February 26, 2008, 11:42pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-children/130243/2 "2008-02-26T23:42:45Z")

</div>

For has\_one:

validates\_presence\_of :child\_record  
validates\_associated :child\_record

For n children:

You should be able to use a validation on the model

validate :number\_of\_children

def number\_of\_children  
errors.add\_to\_base “Can only have n children” if children.length \> n  
end

On Feb 26, 12:43 pm, Sam C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
