First of all, we are gonna need the tools,
Go ahead and register an API key at Recaptcha. Then go ahead and install the plugin/gem at Ambethia's Recaptcha on GitHub.
Once we got those installed and done, first thing first is to setup the API keys.
/config/environment.rb
# Load the rails application
require File.expand_path('../application', __FILE__)
ENV['RECAPTCHA_PUBLIC_KEY'] = '6LetRwwAAAAAAHYInUoOSj2mN_2dafLelpON4VzV'
ENV['RECAPTCHA_PRIVATE_KEY'] = '6LetRwwAAAAAAHYInUoOSj2mN_2dafLelpON4VzV'
# Initialize the rails application
RecapApp::Application.initialize!
Then we are generally gonna use Recaptcha in a form submission. Let's stick it there.
/views/posts/_form.html.erb
#Add this somewhere, note the Raw as Rails 3 automatically escapes html
<%=raw recaptcha_tags %>
Then we will have to take care of the backbone in the controller. So we want Recaptcha to kick in when a user sends a POST request or submit a post.
/controllers/posts_controller.rb
def create
@post = Post.new(params[:post])
respond_to do |format|
if (verify_recaptcha(:model => @post, :message => "The captcha does not match!") && @post.save)
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
format.xml { render :xml => @post, :status => :created, :location => @post }
format.js
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
format.js
end
end
end
The :message option will deal with the error message in the form if the captcha doesn't match.
And there you have it!
2 comments:
What do you mean "#Add this somewhere, note the Raw as Rails 3 automatically escapes html" I'm having this problem and don't know how to fix it. :(
I see what it is now. You must ad raw() around the function.
Post a Comment