Rails 4 simple_captcha无法正常工作

时间:2014-02-12 16:32:30

标签: ruby-on-rails-4 simplecaptcha

我觉得我错过了一些小细节,但我能理解这一点。

我正在尝试将simple_captcha(https://github.com/galetahub/simple-captcha)连接到他们在Rails 4上的项目:

的Gemfile:

gem 'simple_captcha', :git => 'git://github.com/galetahub/simple-captcha.git'

application_controller.rb:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  include SimpleCaptcha::ControllerHelpers
end

.html.erb:

<%= form_for :test, url: tests_path do |f| %>
...
  <p>
    <%= f.simple_captcha :label => "Enter numbers..", :object => "test" %>
      <%= f.submit %>
  </p>
<% end %>

tests_controller.rb:

class TestsController < ApplicationController
...
def create
    @test = Test.new(test_params)
   if  @test.valid_with_captcha?
     @test.save_with_captcha
     redirect_to root_path
   else
     redirect_to tests_path
    end
  end
end

rails生成simple_captcha rake db:migrate ,没有错误。

显示验证码,但不会显示:无论是否正确输入验证码,仍然是重定向到 tests_path 并且文本未被保留。

如果没有验证码文本存储正确,它可以正常工作:

def create
  @test = Test.new(test_params)
  @test.save
  redirect_to root_path
 end
end

1 个答案:

答案 0 :(得分:2)

事实证明,宝石不支持导轨4.为Rails 4工作宝石:https://github.com/pludoni/simple-captcha

我在代码中的错误应该是:

    def create
    @test = Test.new(captcha_params)

    if @test.save_with_captcha
      redirect_to root_path
    else
      if @test.errors.any?
        redirect_to tests_path
      end
    end
  end

  private
  def captcha_params
    params.require(:test).permit(:id, :text, :captcha, :captcha_key)
  end