Re: Create several models at once and validating

You can call validation first, and proceed to saving
only if everything validates:

if @user.valid? && @team.valid?
@user.save(false)
@team.save(false)
end

the ‘valid?’ method does what you’d expect; the
‘false’ paramter to the save method means “don’t do
validation while saving” (since by the time you get to
the save statement, the validation has already
passed).

Cheers,
B Gates

But if I do @user.save and then @team.save, whether
validations on team
failed,
the user is created but team doesn’t and I want non of
them to be
saved.


Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com

B Gates wrote:

You can call validation first, and proceed to saving
only if everything validates:

if @user.valid? && @team.valid?
@user.save(false)
@team.save(false)
end

The only potential problem with this code is that you won’t get
any @team error messages in the view if @user fails to validate.
Instead you’d have to write:

valid_team = @team.valid?
if @user.valid? && valid_team


We develop, watch us RoR, in numbers too big to ignore.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs