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 Clearman
<rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>
wrote:> 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.
> --
> Posted viahttp://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---