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.