Search code examples
ruby-on-rails-4simplecaptcha

Rails 4 simple_captcha not working


I feel like I missed some small detail, but I can understand this.

I'm trying to connect simple_captcha (https://github.com/galetahub/simple-captcha) for their project on 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 generate simple_captcha and rake db: migrate with no errors.

Captcha is displayed, but does not manifest itself: it does not matter is correctly entered captcha or not, is still a redirect to tests_path and the text is not preserved.

Without captcha text is stored properly, it works:

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

Solution

  • As it turned out gem not support rails 4. Work gem for Rails 4: https://github.com/pludoni/simple-captcha

    And I am much mistaken in the code should be something like:

        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