如何在rails中进行reCaptcha验证时阻止表单提交

时间:2017-04-27 06:10:54

标签: ruby-on-rails recaptcha

我在我的rails应用程序上使用Google reCaptcha v2来验证提交表单但我无法弄清楚如何链接reCaptcha验证和表单提交,无论是否检查了reCaptcha表格总是提交。

我也使用recaptcha gem,并根据文档设置了所有内容,看起来好像验证本身有效,它只是与表单提交无关。 / p>

以下是相关代码:

_form.html.erb

<%= form_for([@video, @video.comments.build]) do |f| %>
  <%# Other tags %>
  <%= recaptcha_tags %>
<% end %>

comments_controller.html.erb

def create
    @video = Video.find(params[:video_id])
    @comment = @video.comments.create(comment_params)
    if verify_recaptcha!(model: @comment) && @comment.save
        redirect_to @video
    else
        # I had "render 'new'" here as the documentation did but that caused an error
    end
end

配置/初始化/ recaptcha.rb

Recaptcha.configure do |config|
  config.site_key  = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  config.secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
end

render "new"

生成的错误
Missing template comments/new, application/new with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :arb, :coffee, :jbuilder]}. Searched in: *...

错误似乎是因为没有为评论/新设置任何内容,但我不确定如何添加。

1 个答案:

答案 0 :(得分:1)

初始化.create时,您正在调用@comment.create创建一个新对象并将其保存在一个步骤中,因此您需要在验证重新绑定之前保存它。使用@comment = @video.comments.new(comment_params)