现在的位置: 首页 > 综合 > 正文

Simple Captcha in rails 3

2018年04月19日 ⁄ 综合 ⁄ 共 2021字 ⁄ 字号 评论关闭

Simple Captcha in rails 3

By , December 10, 2010 2:41 am

Here I will show you how to add captcha in rails 3 application:

Download Simple captcha plugin from the git :
click here

rails plugin install https://github.com/galetahub/simple-captcha.git

Generate Simple Captcha

rails generate simple_captcha
rake db:migrate

Generate scaffold of MODEL

rails g scaffold Model

Captcha code can be added two way . 1. Controller based 2. Model based

Controller Based

Include simple captcha in app/controllers/application.rb

ApplicationController < ActionController::Base
    include SimpleCaptcha::ControllerHelpers
end

Add captcha code in form page

<%=show_simple_captcha%>

Check captcha authentication in controller

def create
  if simple_captcha_valid?
    do something....
  else
    do something....
  end
end

Model Based
Add captcha in model

class Model < ActiveRecord::Base
   apply_simple_captcha
end

In Form page

<%= show_simple_captcha( :label => "human authentication",:object => "object") %>

In controller

 @object.valid_with_captcha?
or
@object.save_with_captcha

ADD I18n

simple_captcha:

  message:

    default: "Secret Code did not match with the Image"

    user: "The secret Image and code were different"

If application is in ruby 1.9.* then you need to require some changes in plugins otherwise you will not able to see captcha image and get following error

"TypeError (can't convert nil into Integer):"

Changes in /simple-captcha/lib/simple_captcha/image.rb
At line number 47: Comment class Tempfile

#class Tempfile < ::Tempfile

# Replaces Tempfile's +make_tmpname+ with one that honors file extensions.

# def make_tmpname(basename, n = 0)

# puts "**********************Base name: #{basename}"

# extension = File.extname(basename)

# puts "**********************Extension: #{extension}"

# puts "********************** SPRINFG #{File.basename(basename, extension)},#{$$},#{n.to_i}#{extension}"

#

# # sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n, extension)

# sprintf("%s%d-%d%s", File.basename(basename, extension), $$, n, extension)

# #"%s,%d,%d%s", File.basename(basename, extension), $$, n, extension

# puts "**********************Base name: #{basename}"

# end

# end


At line number 68: replace with below code

dst = Tempfile.new(['simple_captcha','.jpg'])

Hope this helps to solve above problem in rails 3.

抱歉!评论已关闭.