Is there a way to validate a model w/o saving it?

I have some code in my controller which looks like this:

if request.post? and @account.save and @user.save
    ...
end

and in my Account and User models I have many :validates, like so

account.rb
validates_presence_of :subdomain, :on => :create
validates_uniqueness_of :subdomain, :on => :create, :message => “is
already being used”
validates_exclusion_of :subdomain, :in => %w{ www blog weblog forum
info }, :message => “invalid subdomain”

user.rb
validates_presence_of :login
validates_uniqueness_of :login, :on => :create
validates_length_of :login, :within => 3…40
validates_confirmation_of :password, :if => Proc.new { |u|
u.password.size > 0}
validates_length_of :password, :within => 5…40, :on => :create

My problem is that if there are issues with the user validation, the
account has already been saved, so when the user fixes the fields and
resubmits the validates_uniqueness_of check fails for the account
(since it was already saved to the db).

I’ve looked through the rdoc for ActiveRecord::Base and don’t see a
method which would validate in the same way that the create_or_update
method does.

Thanks,
Sean

Your controller code would be helpfull,

You could try looking up the user before you do the save. That way, if
she
already exists, just update her info. If she doesn’t exist, create a
new
one. That would get around the uniqueness test. then you can go on to
save
the other data like usual.

matt

In the action responsible for updating the user/account, you need to
find the existing record and update it, not create a new one.

Something like this may be what you’re after…

if request.post?
@user = User.find(params[:id])
@user.update_attributes(params[:user])
@user.account.update_attributes(params[:account])
end

-Jonny.

Sean M. wrote:

I have some code in my controller which looks like this:

if request.post? and @account.save and @user.save
    ...
end

and in my Account and User models I have many :validates, like so

account.rb
validates_presence_of :subdomain, :on => :create
validates_uniqueness_of :subdomain, :on => :create, :message => “is
already being used”
validates_exclusion_of :subdomain, :in => %w{ www blog weblog forum
info }, :message => “invalid subdomain”

user.rb
validates_presence_of :login
validates_uniqueness_of :login, :on => :create
validates_length_of :login, :within => 3…40
validates_confirmation_of :password, :if => Proc.new { |u|
u.password.size > 0}
validates_length_of :password, :within => 5…40, :on => :create

My problem is that if there are issues with the user validation, the
account has already been saved, so when the user fixes the fields and
resubmits the validates_uniqueness_of check fails for the account
(since it was already saved to the db).

I’ve looked through the rdoc for ActiveRecord::Base and don’t see a
method which would validate in the same way that the create_or_update
method does.

Thanks,
Sean