This has probably been done to death, but for the sake of Random Google Searches (RGSs), here is a quick run through about how to do reCAPTCHA with Rails.
First off, you need to register at recaptcha.net. Then you need to add your domain and get two keys (one public, one private). I created two sites once registered, one for my development environment (localhost), and one for production.
Second, there is a Rails plugin. It’s on GitHub. So install it like this:
$ ./script/plugin install git://github.com/ambethia/recaptcha.git
Third, take those public and private reCAPTCHA keys and place those suckers in your environment.rb or appropriate environment file. Here’s what I added to the bottom of my development.rb, replacing the ‘MY_PUBLIC_KEY’ and ‘MY_PRIVATE_KEY’ with the keys from recaptcha.net (but keep the single quotes):
ENV['RECAPTCHA_PUBLIC_KEY'] = 'MY_PUBLIC_KEY'
ENV['RECAPTCHA_PRIVATE_KEY'] = 'MY_PRIVATE_KEY'
Fourth, find the place in your views where you want the reCAPTCHA box to appear. The plugin defines a special view helper named
recaptcha_tags. Here’s a basic example:
Ask a Question -- Get an Answer!
<% form_for(@question) do |f| %>
Question: <%= f.text_field :question %>
Human Test: <%= recaptcha_tags %>
<%= f.submit "Ask Question" %>
<% end %>
And here’s what it that basic html looks like:
Each page load will embed code that pings the reCAPTCHA API and generates a new captcha. Note that there are some extra options on
Lastly, we have to handle the verification in the controller. Here’s how I integrated it:
@question = Question.new(params[:question])
if verify_recaptcha() and @question.save
redirect_to :action => 'show', :permalink => @question.permalink
render :action => 'new'
The verify_recaptcha() method will take params from the POST request, ping recaptcha.net, and then return true or false. Then you can handle it however you want (here in the same block as model validation). If the captcha fails, it’ll render the new page again, where a small error message will show up in the reCAPTCHA box.