On 8/18/06, Chris Abad <[EMAIL PROTECTED]> wrote:
Let's say I have two model objects being created by the same form.
We'll call them User and Account. How would you create both or
neither (validations in one may fail)?

Hey, Chris. Interesting question. I haven't personally dealt with this
too closely, but I have a few ideas you might check out.

If you're just checking for validity, try calling #valid? on the objects.

@account = Account.new(params[:account])
@user = User.new(params[:user])
if @account.valid? and @user.valid?
  # do cool stuff...
else
  # show error messages...
end

This way, you validate everything before you save anything. This
probably doesn't help for all cases if you want to catch other errors
and exceptions that might happen when you try to save the objects.

If the objects are related with ActiveRecord Associations, it might
make sense to build the objects in memory and then validate the one
object that contains the rest. I assume that would validate all the
associated objects? Again, haven't personally tried it but it's worth
a look.

@account = Account.new(params[:account])
@account.build_user(params[:user])
if @account.valid?
  # stuff...
else
  # try again
end

You might also look into transactions.
http://wiki.rubyonrails.org/rails/pages/HowToUseTransactions

Let us know what you settle on. :-)

--
Nick Zadrozny
_______________________________________________
Sdruby mailing list
[email protected]
http://lists.sdruby.com/mailman/listinfo/sdruby

Reply via email to