How to validate presence of children?

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.

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. [email protected]