How to get detailed error messages from rails console?

Viewed 12673

Say I wish to create a user from console with an email which already exists. If I do User.create(...)

Because of model validations (uniqueness in this case). create fails and the output in rails console will say: rollback transaction (user is not saved)

For the purpose of testing. Is their a way I can get the explicit error which triggered the rollback? In this case it would say something like: "ROLLBACK: email is not unique".

3 Answers

If you mean by using "rails console", I hope and this small example is useful for you:

Model Student (student.rb):

class Student < ApplicationRecord
  validates :name, presence: true, length: {minimum: 5, maximum: 50}
end

And at Rails console ($ rails console) do something like this:

> student = Student.create(name:"alba")
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
 => #<Student id: nil, name: "alba">

> student.errors.any?
 => true

> student.errors.full_messages
 => ["Name is too short (minimum is 5 characters)"]

Hope this helps.

Related