Captcha in Ruby on Rails – Customize the use of captcha in the plugin validates_captcha
October 24, 2006 at 6:59 pm 50 comments
Hello Everyone !!
I have released a captcha plugin Simple Captcha. It is really simple to implement, and provides a cool feature of multiple styles of images.
Previous Post for validates_captcha
To implement captcha in RubyonRails, validates_captcha plugin can be a good option but a small customization i need with this plugin was to use it on some specific action and not to be validated the captcha field every time an instance of the model is saved or updated.
Here is a small work-around for its customization…
How to use customized captcha in RoR ?
Install the plugin validates_captcha in your rails application by running this command from the root of your application
ruby script/plugin install http://svn.2750flesk.com/validates_captcha
Make sure that you can now see the directory vedor/plugins/validates_captcha.
Now run these commands from your application root to make the image and data directories
ruby script/generate captcha store_directory ruby script/generate captcha image_directory
Here is the complete API for the usage of this plugin. I am describing the same idea as given in this API but in a bit more specific means.
Lets consider a model User in which we will implement the captcha.
Add the following code in the file app/models/user.rb
class User < ActiveRecord::Base
validates_captcha :if => :request_captcha_validation?
attr_accessor :request_captcha_validation
def request_captcha_validation?
(self.request_captcha_validation==true)? true : false
end
end
Handle View and Controller
Add the code in the view inside your existing form.
<% c = prepare_captcha :type => :image -%> <%= captcha_hidden_field c, 'user' %> <%= captcha_image_tag c %> <%= captcha_label 'user', 'Type in the text from the image above' %> <%= captcha_text_field 'user' %>
Your controller will look like
def save
# the line in bold represents that you need captcha validation.
# if captcha validation is not required then remove this line from your controller.
@user = User.new(params[:user])
@user.request_captcha_validation = true
@user.save
end
However image is too noisy and it contains repeated strings.
To improve the quality of images generated by the plugin validates_captcha visit Here.
Entry filed under: captcha, image, ror, Ruby on Rails, validations. Tags: .










Rss Feeds
1.
Chintan Shah | November 14, 2006 at 10:55 am
it’s givng me an error like
d Showing app/views/comment/_comment_template.rhtml where line #75 raised:
directory script/../config/../var/data does not exist
Extracted source (around line #75):
72:
73:
74:
75: :image -%>
76:
77:
78:
2.
Chintan Shah | November 14, 2006 at 10:56 am
Showing app/views/comment/_comment_template.rhtml where line #75 raised:
directory script/../config/../var/data does not exist
Extracted source (around line #75):
72:
73:
74:
75: :image -%>
76:
77:
78:
3.
Sur Max | November 14, 2006 at 10:59 am
Hi Chintan,
sorry for that !!
I havent given the information to generate the image and data directory…
please run these commands from the root of your application.
ruby script/generate captcha store_directory
ruby script/generate captcha image_directory
Restart the server and test if it is working !!
4.
Chintan Shah | November 14, 2006 at 11:02 am
thnx a lot for a giving a fast reply
5.
Chintan Shah | November 14, 2006 at 2:56 pm
i got an error when i upload the project on the production server like,
Postscript delegate failed Extracted source (around line #6):
3:
4: :image -%>
5:
6:
7:
8:
9:
6.
Sur Max | November 14, 2006 at 4:37 pm
Make sure u have installed RMagick, ImageMagick etc… properly on the linux server…
Whats you local machine… is it windows ? Is it running fine on your local machine ?
7.
Paddy | November 14, 2006 at 7:17 pm
I am trying to validate the captcha in the controller and getting the following error
undefined method `captcha_valid?’ for #
After taking a deep look in the API, I see that the following file is missing and I have even updated the plugin and in fact I even uninstalled it and reinstalled the plugin and still couldn’t find the file.
lib/add_captcha_to_action_controller.rb
Can some body please email me the file to the following email address:
paddy[dot]in[at]gmail[dot]com.
or can tell me where to download this file.
Many Thanks!
-Paddy
8.
Sur Max | November 14, 2006 at 7:37 pm
Hi Paddy,
there is no such file in the plugin validates_captcha.
How did u find that we need it ?
Are you getting any error regarding the missing file ?
9.
Paddy | November 15, 2006 at 3:40 am
Thank you for your response Sur!
I am getting “undefined method `captcha_valid?’ for #HomeController”
I am trying to validate the captcha in the controller and so there is a method named “captcha_valid?” and it resides in the file ” lib/add_captcha_to_action_controller.rb ”
Here is the API and you can access it:
http://dev.2750flesk.com/validates_captcha/classes/FleskPlugins/Captcha/Verifications/InstanceMethods.html
Thank you
-Paddy
10.
Sur Max | November 15, 2006 at 5:05 am
Hi Paddy,
If you only need to check valid , you can do it by checking @user.valid? (@user or an instance of your model class).
could you send me the code that how you are using the plugin, i havent tried it as controller centric way yet.
11.
Chintan Shah | November 15, 2006 at 5:14 am
thnx a lot Sur
12.
Paddy | November 15, 2006 at 5:16 am
Thank you for your response Sur!
I don’t use any model for this as its just plain contact me form and I’ll be just accessing it via params only and its a Action Mailer.
I don’t have the code right now and will paste in few hours of time.
Thank you
-Paddy
13.
Paddy | November 15, 2006 at 6:03 pm
Thanks sur!
I just created a dummy model and it works!
Thank you
-Paddy
14.
Erwin K. | November 18, 2006 at 10:19 am
Thanks a lot.. running fine…
A small problem I don’t know yet how to solve it :
on error, my input text field got a colored background, using a CSS class
.fieldWithErrors input, .fieldWithErrors select {
background-color: #ffdfdf;
}
It’s working fine for all my form fileds except the captcha one :
mine..
td class=”label” Email address: /td
td class=”label” %= f.text_field :email_address, { :maxlength => “60″, :size => “30″, :tabindex => “4″ } % /td
captcha
td class=”label” %= captcha_label “user”, “Tapez le texte de l’image” % /td
td class=”label” %= captcha_text_field “user” % /td
any clue ?
Erwin
15.
Erwin K. | November 18, 2006 at 10:28 am
On error the input field should be in a DIV with class : fieldWithErrors…
where is this field generated ?
16.
rossnet | November 21, 2006 at 2:28 pm
hi & thanks for the nice article,
i’ve probably a newbie question ,-) as I get a:
undefined method `validates_captcha' for AppointmentController:Classwhile using the captcha in a littlebit different approach
validates_captcha
nly => [ :sendemails ](so i don’t define the additional method and the accessor)
the necessary directories have been generated and i’ve restarted the server. still it seems my rails environment doesn’t really know about this validation? do i need to add some sort of ‘require’ somewhere
thanks,
rossnet
17.
Sur Max | November 21, 2006 at 2:35 pm
Hi rossnet,
I think u are implementing the captcha in controller… i am not sure if u want in that way or not but make it confirm that if u want captcha as controller centric then what to define exactly.
However we put validates_captcha in the model class.
What say?
18.
rossnet | November 21, 2006 at 4:19 pm
D’oh! Stupid me…
Thanks for the quick reply – of course you’re absolutly right. There doesn’t seem to be a “:only” clause like on filters on the validations, so I implemented it the way you described above
I think I still was confused after I learned in a couple of hours of slight frustration that you need to be very careful what’s stored in a session when you change something in the model definition, as this change isn’t reflected until you restart the session (or maybe put the derived object again into the session).
Cheers again,
rossnet
19.
Sur Max | November 21, 2006 at 4:56 pm
Thanks Rossnet…
======================================
Hi Erwin K..
sorry, i dont know how i skipped your comment !!
Well, i havnt got the time to to go through this stylesheet issue, however i will try it and hope to get some work-around.
20.
Laurent | November 25, 2006 at 7:04 pm
I have a problem when testing the Captcha :
You have a nil object when you didn’t expect it!
The error occured while evaluating nil.new
Extracted source (around line #23):
23: :image -%>
vendor/plugins/validates_captcha/lib/add_captcha_to_action_view.rb:34:in `prepare_captcha’
#{RAILS_ROOT}/app/views/user/signup.rhtml:23:in `_run_rhtml_user_signup’
Any idea ..I’m on Mac OS X, installed ImageMagick and rmagick
21.
Sur Max | November 26, 2006 at 7:08 pm
Hi Laurent,
could you show me the code which you are using to implement the captcha and so i try to figure out that whether the problem is with the code or installation of any of gems or libraries per se.
22.
Laurent | November 30, 2006 at 7:27 am
It’s OK in fact i had problems with installation of RMagick using Ruby (1.8.2) preinstalled on Mac OS X
I reinstalled Ruby 1.8.5 , RMagick now it works
But i have a problem with the captcha : the image generated includes a lot of noise and i do not see any word inside !! Any idea?
23.
Sur Max | November 30, 2006 at 7:30 am
Yes Laurent,
I have the idea and i already published that.
View this post to improve the image quality and generating random string images.
24.
Martin Bilski | December 6, 2006 at 6:48 pm
With regard with a “fieldWithErrors” DIV. Here’s what worked for me:
1. Open vendor/plugins/trunk/lib/add_captcha_to_active_record.rb
2. For every “errors.add” method call, replace ‘captcha’ with ‘captcha_validation’, e.g.
errors.add(‘captcha’, options[:message])
becomes:
errors.add(‘captcha_validation’, options[:message])
(There are 3 such places in the version of the plugin I have).
Note: I’m also using the “error_messages_for” plugin to replace the default error message:
{ ‘captcha_validation’ => “Verification failed; please try again.” }, :defaults=> false } %>
You need to install the other plugin first if you want to use the code above in your view (remember to restart the server).
Just my $0.0001
Best,
MB
25.
Renuka | December 12, 2006 at 12:27 pm
Hi,
I have done all steps correctly to setup the captcha plugin, and everytime I start the web server (mongrel, webrick, lighttpd)… It comes up with the following error.
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:1129:in `method_missing’: undefined local variable or method `validates_captcha’ for User:Class (NameError)
from /sites/pv/config/../app/models/user.rb:21
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:140:in `load’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:56:in `require_or_load’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:30:in `depend_on’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:85:in `require_dependency’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:98:in `const_missing’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:131:in `const_missing’
from /usr/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/observer.rb:131:in `observed_class’
… 17 levels…
from /usr/lib/ruby/gems/1.8/gems/mongrel-0.3.13.4/bin/mongrel_rails:85:in `run’
from /usr/lib/ruby/gems/1.8/gems/mongrel-0.3.13.4/lib/mongrel/command.rb:211:in `run’
from /usr/lib/ruby/gems/1.8/gems/mongrel-0.3.13.4/bin/mongrel_rails:231
from /usr/bin/mongrel_rails:18
—-
But, if I comment the validates_captcha line in my user.rb model, the server starts successfully. And, then I can uncomment and it will generate the captcha successfully.
I would like to have a permanent solution, so that I don’t have to comment/uncomment validates_captcha line everytime I restart server.
I am so stuck, that a quick answer will get me going. Waiting for your reply.
26.
Sur Max | December 12, 2006 at 4:35 pm
Hi Renuka !!
Well, no idea dear… Haven’t faced such problem.
27.
Sur Max | December 17, 2006 at 2:14 am
Thanks Martin !!
28.
Jesse | January 7, 2007 at 1:26 am
I keep getting this error: “Can’t measure text. Are the fonts installed? Is the FreeType library installed?”
I installed RMagick using this tutorial but I’m still getting the same message.
Any ideas? Thanks.
29.
lil mp3 scrappy | January 19, 2007 at 10:47 am
HI! I just wanted to tell you that i really liked your site and you did a great job with it. Just for your notehttp://mp3-safe-download.org
has great music there.
30.
Liana | January 25, 2007 at 12:17 am
From the code in the view inside the existing form…
When I use:
:image -%>
I get the error (even though RMagick is correctly installed):
uninitialized constant Magick
When I use:
I get the error:
undefined method `prepare_captcha’ for #:0x4b62da4>
What’s Up?
31.
Sur Max | January 25, 2007 at 3:50 am
Hi Liana !!
Just wait till the next week, i m going to launch my own captcha
plugin which is much more simpler.
Also give me ur genuine mail so that i can inform u there also…
mail me at sur.max(at)gmail.com
32.
Brian | February 11, 2007 at 3:22 am
Sur,
I want to use the Captcha validation on a email contact form, so I do not have a model object per se. Do you know how to use this plugin in that case?
Thanks,
Brian
33.
Sur Max | February 11, 2007 at 3:40 am
Hi Brian !!
I have moved this blog on Expressica.com and i have released a new captcha plugin for rubyonrails applications as Simple Captcha which provides both the ways to implement as model based or controller based captcha. And also it provides a variety of image styles too.
34. EXPRESSICA » How to improve the image quality and generate random string image in the plugin validates_captcha | February 11, 2007 at 7:45 pm
[...] Validates captcha is a good plugin to implement captcha in your rails application. However i found that there is repetition of the string of the image and the quality of image is not that good. To get a good quality image and random string something like this replace the code of the file /vendor/plugins/validates_captcha/lib/captcha_challenge.rb with the following code… [...]
35.
Captch validation for ?User having login engine | February 14, 2007 at 9:34 am
`@user[captcha_validation]‘ is not allowed as an instance variable name
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:328:in `instance_variable_get’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:328:in `object’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:338:in `value_before_type_cast’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:253:in `to_input_field_tag’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:160:in `text_field’
#{RAILS_ROOT}/vendor/plugins/validates_captcha/lib/add_captcha_to_action_view.rb:100:in `captcha_text_field’
#{RAILS_ROOT}/vendor/plugins/login_engine/app/views/user/_image_validate.rhtml:7:in `_run_rhtml_D__work_Rails_workspace_zmobs_vendor_plugins_login_engine_app_views_user__image_validate’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/base.rb:316:in `send’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/base.rb:316:in `compile_and_render_template’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/base.rb:292:in `render_template’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/base.rb:251:in `render_file’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/base.rb:266:in `render’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/partials.rb:59:in `render_partial’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_controller/benchmarking.rb:29:in `benchmark’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/1.8/benchmark.rb:293:in `measure’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/1.8/benchmark.rb:307:in `realtime’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_controller/benchmarking.rb:29:in `benchmark’
D:/software/InstantRails-1.4-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/partials.rb:58:in `render_partial’
#{RAILS_ROOT}/vendor/plugins/login_engine/app/views/user/signup.rhtml:10:in `_run_rhtml_D__work_Rails_workspace_zmobs_vendor_plugins_login_engine_app_views_user_signup’
36.
Sur Max | February 14, 2007 at 9:37 am
Use this Simple Captcha, its really simple to implement and gives good images.
37.
Wang | February 20, 2007 at 6:22 am
Hi Sur,
I tried to use validates_captcha plug-in with Windows XP. Is this plug-in supoort window platform? After I install and config this plug-in. Some pages can’t be find with error as
I am using Windows XP and Webrick server with Rails 1.2.1.
Thanks
Max Wang
38.
Sur Max | February 20, 2007 at 6:48 am
Hi you can use the plugin Simple Captcha …
I have tried it on every platform and it runs fine. You will have to install RMagick gem available to on RubyForge.
39.
Wang | February 21, 2007 at 9:59 pm
Thansk for suggestion. Simple Captcha is great and simple.
40.
uday | February 23, 2007 at 11:29 am
ERROR: Could not load RMagick. CAPTCHA plugin not available.
uninitialized constant CaptchaGenerator::AngryMidgetPluginsInc
i have installed RMagick even though i am geting this msg can any body help me out
41. Vinsol.com » Blog Archive » How to improve the image quality and generate random string image in the plugin validates_captcha | February 24, 2007 at 12:23 pm
[...] Validates captcha is a good plugin to implement captcha in your rails application. However i found that there is repetition of the string of the image and the quality of image is not that good. To get a good quality image and random string something like this replace the code of the file /vendor/plugins/validates_captcha/lib/captcha_challenge.rb with the following code… [...]
42.
Sur Max | February 26, 2007 at 5:05 pm
Hi Uday !!
Just try to use the plugin Simple Captcha
43.
uday | March 3, 2007 at 10:17 am
I need your help please
I have installed simple captcha and after that i started the webrick server but the server is not starting but giving the following error can you tell what is the exact problem and what i need to do waiting for your reply
Booting WEBrick…
/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.1/lib/active_support/dependencies.rb:266:in `load_missing_constant’: uninitialized constant Magick (NameError)
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.4.1/lib/active_support/dependencies.rb:452:in `const_missing’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.4.1/lib/active_support/dependencies.rb:464:in `const_missing’
from ./script/../config/../vendor/plugins/simple_captcha/lib/simple_captcha_image.rb:3
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.4.1/lib/active_support/dependencies.rb:495:in `require’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.4.1/lib/active_support/dependencies.rb:342:in `new_constants_in’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.4.1/lib/active_support/dependencies.rb:495:in `require’
from script/../config/../vendor/plugins/simple_captcha/init.rb:3:in `load_plugin’
… 17 levels…
from /usr/lib/ruby/gems/1.8/gems/rails-1.2.2/lib/commands/server.rb:39
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require’
from ./script/server:3
from -e:4
44.
Sur | March 3, 2007 at 2:15 pm
Seems like you have not installed RMagick ruby gem.
45.
uday | March 5, 2007 at 6:54 am
Hi
Thanks for your help now validate captcha is working fine actully it was rmagick problem now every thing is fine great work keep it up
Thanks and regard
uday pratap
46.
Chintan Shah | March 9, 2007 at 12:19 pm
1) Tell me the difference between 2 versions
2) and if i want to use older version then, will it creates any problems?
47.
Sur Max | March 10, 2007 at 10:54 am
Hi Chintan,
validates_captcha is written by Tore Darell and Simple Captcha by me
48.
monica | April 23, 2007 at 4:49 pm
thats great!!!! thank you!!!
49.
t2ornado | July 12, 2007 at 5:32 pm
Hi Sur,
After installing validates_captcha when i try to create image and data directory,
ruby script/generate captcha store_directory
ruby script/generate captcha image_directory
it says “Couldn’t find ‘captcha’ generator”
Please help
Thanks
Amit
50.
Sur Max | July 13, 2007 at 4:37 am
Hi t2ornado,
You can try using Simple Captcha plugin, which is much easy and simple to use.
Thanks.