简体   繁体   中英

Ruby on Rails - Adding a human security field into the simple_form gem?

I currently have a form created using the simple_form gem in Ruby on Rails but I would like to add a sort of 'What is 1+1?' question and input field as the last question to remove the risk of bots etc. How would I add this function into my form?

My form consists of the following:

<%= 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 %>

You can add a validation to your model like this:

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

And then in your form:

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

Don't forget to add :human_sum to your permitted params in your controller as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM