views:

669

answers:

1

I have a user registration form, and wanted to write a human detecting "captcha" into my register method. I decided to create a simple math question for users to answer (this should work for my purposes).

How do I write a validation that checks the value of this field? I wrote a validate method in my model file as follows:

def validate
  errors.add(:humanproof, "is not the right answer") if humanproof != 4
end

However since :humanproof is not part of the user model, the "humanproof" variable isn't available there.

What is the best way to access the humanproof variable?

+3  A: 

What you can do is add a virtual attribute. Check out this screencast from RailsCasts.

Basically you want to add an attribute to your class. Because you don't have to perform any logic with it you can just use the built Ruby method form instance variables.

 class Foo < ActiveRecord::Base
   attr_accessor :humanproof

   def validate
     errors.add(:humanproof, "is not the right answer") if humanproof != 4
   end

This adds an attribute to your class that is not saved to the database and is attached to the object for the duration of the request.

vrish88