【问题标题】:Rails simple-captcha validation never works? Even when correctRails 简单验证码验证从不工作?即使正确
【发布时间】:2015-04-20 08:34:04
【问题描述】:

我正在尝试在我的应用程序中将 simple-captcha2 实现到一个表单中,但是当我使用不正确的验证码对其进行测试时,我在 SubmitsController#create 中得到一个 NoMethodError , nil:NilClass 的未定义方法“错误”

宝石:https://github.com/pludoni/simple-captcha
我正在使用 Rails 4

我已经在我的应用程序中实现了 simple-captcha2,但我总是收到一个错误,说验证码与图像不匹配,即使它匹配! 经过大量调试,我仍然无法找出原因。 我确信我已经正确完成了 gem 文档中的步骤。

我的提交控制器:

class SubmitsController < ApplicationController
before_action :captchaa, only: [:create]

def new
  @submit = Submit.new
end

def create
    @submit = Submit.new(submit_params)
    if @submit.save_with_captcha
      redirect_to(:action=>'thanks')
    else
      render('new')
    end
end
...
private
 def captchaa
   if simple_captcha_valid?
   else
     render('new')
   end
 end
end

我的表单视图:(我在这里也遇到了与@submit.errors 相同的错误)

<% if @submit.errors.any? %>
  <ul>
    <% @submit.errors.full_messages.each do |msg| %>
    <li>
      <%= msg %>
    <% end %>
    </li>
  </ul>
<% end %>
...form fields
<%= show_simple_captcha %>

我的模型包括:

apply_simple_captcha :message => "The secret Image and code were different", :add_to_base => true

我的应用程序控制器包括:

include SimpleCaptcha::ControllerHelpers

也许我错误地将验证错误添加到错误数组? 有谁知道我做错了什么?

非常感谢!

【问题讨论】:

  • 您没有按照文档包含 captcha_helper。 include SimpleCaptcha::ControllerHelpers
  • 我的应用程序控制器确实包含 SimpleCaptcha::ControllerHelpers。我已将其添加到帖子中
  • 我也有这个问题,但只在 Chromium 上,它在 Firefox 中运行良好。

标签: ruby validation ruby-on-rails-4 error-handling captcha


【解决方案1】:

根据文档,您需要从模型https://github.com/pludoni/simple-captcha#model-options添加错误

class Submit < ActiveRecord::Base
  apply_simple_captcha :message => "The secret Image and code were  different", :add_to_base => true
end

你的控制器的创建动作应该是这样的,

def create
  @submit = Submit.new(submit_params)
  if @submit.save_with_captcha
    redirect_to(:action=>'thanks')
  else
    render('new')
  end
end

save_with_captcha?将像保存一样工作,还将验证验证码。如果它在模型中发现任何错误代码将添加错误。查看https://github.com/pludoni/simple-captcha#saving-with-captcha 了解更多详情。希望这可以帮助。

【讨论】:

  • 感谢您的帮助,非常感谢!不幸的是,添加这些更改后我仍然收到错误。
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 2014-01-08
  • 2016-06-15
  • 1970-01-01
相关资源
最近更新 更多