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

ActiveRecord code challenge: Build a custom validator that ensures that no Contactโ€™s last_name is Evil.

What is the solution to this? I am trying the following to no avail. Thanks for your help.

class Contact < ActiveRecord::Base
   validate :check_last_name
   def check_last_name
     if last_name => "Evil"
     error.add(:last_name, " is not allowed")
   end
 end

OR

class Contact < ActiveRecord::Base
   validate :check_last_name
   def check_last_name
     if last_name.includes?("Evil")
     error.add(:last_name, " is not allowed")
   end
 end

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi, gbp The 2nd solution is almost correct, though there're a few things need to be fixed.

  • you missed the a closing end for if condition
  • it's errors.add, not error.add
  • also, you use the String method includes? here, but we are NOT checking whether the last_name includes the word Evil, we are checking whether it equals to Evil.
class Contact < ActiveRecord::Base
   validate :check_last_name
   def check_last_name
     if last_name == "Evil"
       errors.add(:last_name, " is not allowed")
     end
   end
 end

William, thank you!