从 Recaptcha 站点(几乎)....我在 Rails 4 中使用 Devise(显然是硬包)..不,太容易了。程序适用于任何红宝石、任何导轨和设计(或没有设计)。在 ruby/rails/devise 1.9.3/3.2.x/2.2.1 & 2.0.x/4.0.x/3.2.4 中测试,最后一个没有设计。
编辑下一个文件:
宝石文件
gem 'ruby-recaptcha'
# bundle install
config/initializers/credentials.rb (此路径中的任何文件都可以)
# Set constants
RCC_PUB = "your_public_key"
RCC_PRIV= "your_private_key"
# re-start server. Try to keep safety this data using ENV vars.
app/views/devise/registrations/new.html.erb(或您喜欢的形式)
# form
<%= simple_form_for(resource, as: resource_name, :url => registration_path(resource_name) do |f| %>
<%= f.input :email, autofocus: true, required: true %>
...
<!-- Add next line -->
<div id="captchadiv"></div>
<%= f.button :submit, "Register", class: 'btn btn-danger' %>
<% end %
在同一文件的末尾(可以在 awesome_funcs.js.erb 文件中)
<script type="text/javascript" charset="utf-8">
$(function () {
function showRecaptcha() {
Recaptcha.create("<%= RCC_PUB %>", "captchadiv", {
theme: "white",
lang: 'en'
});
};
showRecaptcha();
});
</script>
还有一个小技巧,app/controllers/application_controller.rb
# On top
include ReCaptcha::AppHelper
before_action :configure_permitted_parameters, if: :devise_controller?
# If already you have this method or any other with before_filter
# Into method
protected
def configure_permitted_parameters
if controller_name == "registrations" && action_name == "create"
# Rails 3: If you prefer, put this into registrations#create method
unless validate_recap(params, User.new.errors) # Or your model
# wrong input is handled here
flash[:error] = "Text from images doesn't match with your input"
redirect_to :back # or other stuff
# As my submit is with Ajax, I do a render instead redirect:
# render :json => {other: "recaptcha_failed"}
# In success callback I evaluate response and Recaptcha.reload() paints a new recaptcha.
end
end
....
# trick: do everything before params sanitizers
end
当我们使用 Ajax 插件时,最后,添加 app/views/layouts/application.html.erb (就在正文结束之前)
<body>
...
...
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
</body>
而已。你有recaptcha
建议:如果您使用 Ajax 进行提交,您可以使用 Recaptcha.reload() 的成功回调,以防图像和输入不匹配。
其他,如果您的表单是“remote: true”,您可以在您的views 目录中的create.js.erb 文件中的“create”方法之后使用上述行为。
重要提示:在某些项目中,当表单从链接到达时,Recaptcha 不会出现。尝试将启动器链接定位到 div 或在父 div 中添加“data-no-turbolink”。我在 Rails 4 中遇到了这个问题。