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

Validation MVC ActiveRecord

Can't figure out the answer????

 class Contact < ActiveRecord::Base

   validate :last_name

   def last_name
     self.errors.add(:last_name, 'evil')
   end
 end

Added answer below!

2 Answers

Kang-Kyu Lee
Kang-Kyu Lee
52,045 Points

I think this challenge would be about Active Record Custom Validation by Custom Method (see Guides 6.2). It looks an if statement was needed in the method also. And it seems the code above didn't pass because this name of local variable cannot be the same with method name in Ruby.

I already tried the custom validate method:

validate :method

def method
  if last_name.include?("Evil")
    errors.add(:last_name, "Last name can't be 'Evil'")
  end
end

but this didn't work :'( I tried lots of ways including the rails guide. The answer I gave was the only one that passed :p

So if you can complete the challenge another way go ahead and post it and I will mark it best answer.

And the code above did past... Hints answer: etc

Kang-Kyu Lee
Kang-Kyu Lee
52,045 Points

Hi Michael - However that's weird. Was it really not passing?

I just tried it myself and passed with your code.

validate :method

def method
  if last_name.include?("Evil")
    errors.add(:last_name, "Last name can't be 'Evil'")
  end
end

What I tried also just in case,

 class Contact < ActiveRecord::Base
   validate :method_name

   def method_name
     if last_name == "Evil"
       self.errors.add(:last_name, "message")
     end
   end
 end

Haha, that's so stupid I I don't know man? Beats me, I tried that and still doesn't work.

So if the answers above don't work just do:

  validates :last_name, exclusion: { in: "Evil" }
  // This might pass

This answer passes:

validates :last_name, exclusion: { in: "Evil" }

:p