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

Can't get this code work on challenge 2

Build a custom validator that ensures that no Contact’s last_name is Evil.

contact.rb
 class Contact < ActiveRecord::Base

  validate :evil_in_last_name
    if last_name.include?("Evil")
      errors.add(:last_name, " name already taken")
    end
  end

2 Answers

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

Quite closed, but you need to define a method for the validator; so wrap this block of code

    if last_name.include?("Evil")
      errors.add(:last_name, " name already taken")
    end

into a method named evil_in_last_name.

Final code should be like this

class Contact < ActiveRecord::Base
  validate :evil_in_last_name
  def evil_in_last_name
    if last_name.include?("Evil")
      errors.add(:last_name, " name already taken")
    end
  end
end

Thanks William!!