arnklint Challenges, overcomings, thoughts and inspiration.

Super Simpler SPAM Protection in Ruby on Rails

SPAM bots usually fill in all of the fields in a form, especially those who a user would normally fill in. The plan is to simply trick the bot into filling in a form element, call it “comment”, that is hidden from the real users. When the form is submitted, we will detect if it is filled in. If it is, well, then we have our SPAM bot.

Protect your Rails Application from SPAM

The model:

class Post < ActiveRecord::Base
  attr_accessor :comment # fake attribute used for spam trapping
  validates_length_of :comment, :in => 0..1

And then the view in which we ask the user to not care about a field (if CSS is turned off, otherwise it’s hidden)

<% form_for @comment do |f| %>
   <p style="width: 1px; height: 1px; overflow: hidden;">
     Please leave following field blank:
     <%= f.text_area :comment %>
<% end %>

SPAM means problem

One common problem with popular sites are SPAM bots. You know, the ones that fill in your forms, submit them and hopes to get their word out about what I should buy and click on. But as they don’t really contribute to your site, you’d probably want to get rid of them or don’t have their posts published in the first place.

Don’t let the user suffer from the problem One way to get rid of them are CAPTCHA’s. Even if those are good at differentiate users from bots thus protecting your site, they rarely make life easier for your actual users.

Additional reading