Ruby on Rails - 在simple_form gem中添加人类安全字段?

时间:2015-02-11 11:37:28

标签: ruby-on-rails ruby

我目前有一个使用Ruby on Rails中的simple_form gem创建的表单,但我想添加一种'什么是1 + 1?'问题和输入字段是删除机器人风险的最后一个问题。如何将此功能添加到我的表单中?

我的表单包含以下内容:

<%= simple_form_for @job, html: { multipart: true } do |form| %>
  <h2>Job Position:</h2>
    <%= form.input :position, input_html: { maxlength: 60 }, placeholder: "Job Position", label: false %>
    <%= form.input :company, input_html: { maxlength: 60 }, placeholder: "Company name", label: false %>
    <%= form.input :salary, input_html: { maxlength: 60 }, placeholder: "Salary", label: false %>
    <%= form.input :contract, input_html: { maxlength: 60 }, placeholder: "Contract Type", label: false, collection: ['full time', 'part time', 'internship'], prompt: "Contract Type" %>
    <%= form.input :city, input_html: { maxlength: 60 }, placeholder: "City", label: false %>
    <%= form.input :expirydate, input_html: { maxlength: 60 }, placeholder: "Expiry date", label: false %>
    <%= form.input :description, input_html: { maxlength: 60 }, placeholder: "Full job description", label: false %>
    <%= form.input :apply, input_html: { maxlength: 60 }, placeholder: "How to apply", label: false %>
    <h2>Your Contact Details:</h2>
    <%= form.input :contactname, input_html: { maxlength: 60 }, placeholder: "Contact Name", label: false %>
    <%= form.input :contactemail, input_html: { maxlength: 60 }, placeholder: "Contact Email", label: false %>
    <%= form.input :contactphone, input_html: { maxlength: 60 }, placeholder: "Contact Telephone", label: false %>
    <%= form.button :submit %>
<% end %>

1 个答案:

答案 0 :(得分:2)

您可以像这样在模型中添加验证:

class Job < ActiveRecord::Base
  attr_accessor :human_sum 
  validate :not_a_bot

  private

  def not_a_bot
    if human_sum.to_i != 2 
      errors.add(:human_sum, 'Get out, you bot!') 
    end
  end
end

然后以你的形式:

<%= simple_form_for @job, html: { multipart: true } do |form| %>   
  ...
  <%= form.input :human_sum, label: 'What is 1+1?'
<% end %> 

不要忘记将:human_sum添加到控制器中允许的参数中。