Search code examples
rubysinatradatamapperruby-datamapper

Determine source property of DataMapper validation errors


I’m relatively new to Ruby, Sinatra, and DataMapper, but have a question about DataMapper validation errors.

I know you can see any errors that occur when attempting to save a new row to the database with DataMapper by doing something like the following:

user = User.new username: 'bradleygriffith', password: 'not_my_password'
if user.save
  #success!
else
  user.errors.each do |error|
    puts error
  end
end

What I would like to be able to do is determine on which property the error occurred. This way, for example, I might be able to place error messages next to the appropriate fields in my registration form. That is, I want to know that the registrant entered, say, an invalid username before displaying the error message so that I could place the message along-side the username field.

Is this possible?


Solution

  • The errors object is an instance of DataMapper::Validations::ValidationErrors which has an on method that will return an array containing all the validation error messages for the property you pass as a parameter, or nil if there are no errors. (It looks like those docs don't actually match the implementation).

    user = User.new username: 'joe', :age => 40
    
    if user.save
      #success!
    else
      puts "Username: #{user.username} #{user.errors.on(:username)}"
      puts "Age: #{user.age} #{user.errors.on(:age)}"
    end
    

    produces (with suitable validations set up):

    Username: joe ["Username must be between 4 and 20 characters long"]
    Age: 40