Razer
Razer

Reputation: 8201

Perform only validation of record (without creating it)

I have a model which implements some validation. Is it possible to only do a validation without creating an object?

Edit: The reason why I would need is the following. I need to create two records in a given order, but I have to validate in advance, if the second record would be invalid. If so, it's not allowed to create the first record.

Upvotes: 0

Views: 264

Answers (3)

Brennan
Brennan

Reputation: 5722

@model.valid? will return true if valid, and false if not. If there are failing validations, @model.errors will say why

Upvotes: 2

Jordan Running
Jordan Running

Reputation: 106017

Without even initializing an object? No. Without persisting the object to the database? Yes. Use valid? to check if it's valid, then use errors if you want to know which validation(s) failed.

my_obj = MyModel.new(some_attr: "some_value")

unless my_obj.valid?
  puts "There were errors!"
  p my_obj.errors
end

Upvotes: 2

spickermann
spickermann

Reputation: 106782

Sure, just call valid? on the object:

user = User.new
user.valid? #=> false
user.errors #=> 'name missing...'

Upvotes: 2

Related Questions