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 trialMichael Williams
8,074 PointsValidation 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
2 Answers
Kang-Kyu Lee
52,045 PointsI 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.
Michael Williams
8,074 PointsI 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
52,045 PointsHi 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
Michael Williams
8,074 PointsHaha, 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
Michael Williams
8,074 PointsThis answer passes:
validates :last_name, exclusion: { in: "Evil" }
:p
Michael Williams
8,074 PointsMichael Williams
8,074 PointsAdded answer below!