Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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......