Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby ActiveRecord Basics Validation Errors 2

Sebastian Bachmann
Sebastian Bachmann
7,046 Points

[Done - Solution included] Build a custom validator that ensures that no Contactโ€™s last_name is Evil.

Hi all,

i am stuck here again. And this time i don't even have a clue where to start. This is a bit over my head. So, if someone can push me in the right direction would be awesome.

Regards, Sebastian

3 Answers

Check out the custom validators section of the Rails documentation to get started. In general you're going to want to define a custom validator that will inspect your last_name field and make sure it's not included in a list of unacceptable names.

Sebastian Bachmann
Sebastian Bachmann
7,046 Points

Thank you Geoff Parsons for the hint, i got it working now!

class Contact < ActiveRecord::Base

   validate :last_name_is_not_evil

   def last_name_is_not_evil
     if last_name == "Evil"
       errors.add(:last_name, "This is not a last name")
     end
   end

 end
Jason Shultz
Jason Shultz
4,840 Points

I don't understand why this didn't work:

class GoodnessValidator < ActiveModel::Validator
  def validate(record)
    if record.lastt_name == "Evil"
      record.errors[:base] << "This person is evil"
    end
  end
end

class Contact < ActiveRecord::Base
  validates_with GoodnessValidator
end
Sebastian Bachmann
Sebastian Bachmann
7,046 Points

Hi Jason,

seems like there is an typo in your if clause. I am not able to check your code right now, but if the typo is not the problem, maybe you can post the error message as well.

Regards, Sebastian

check line 3 it's "lastt_name" instead of last_name . Maybe that's the problem......