Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running ActiveRecord validations without saving

I have a collection of ActiveRecord objects. I want to be able to run all the validations for each of these objects without actually saving them to the database. I just want to know if they would be valid were I to save them to the database. In other words, I essentially want to populate the errors data structure for each of my objects. Is there a way to do this? Or perhaps I'm missing something about the lifecycle of the errors collection?

like image 635
kmorris511 Avatar asked Jul 31 '09 17:07

kmorris511


2 Answers

You can do the following to check if a Model is valid:

@user = User.new
if @user.valid?
  #do things

If you want to see what the errors are, you can do:

@user = User.new
unless @user.valid?
  @user.errors.each {|k, v| puts "#{k.capitalize}: #{v}"}

Calling the ".valid?" method runs your validations, putting all of your errors into an ActiveRecord::Errors object, which can be accessed like I did in the example above. Give the examples a try in the Console to get a feel for it if you like.

like image 184
Mike Trpcic Avatar answered Nov 16 '22 01:11

Mike Trpcic


Running the #valid? method on the object will run all validations and populate the errors structure.

dude = Person.new
unless dude.valid?
  # Examine errors
end
like image 32
Andres Jaan Tack Avatar answered Nov 16 '22 01:11

Andres Jaan Tack