Read more

Automatically strip all string fields of an ActiveRecord

Henning Koch
October 18, 2012Software engineer at makandra GmbH

Use the strip_attributes gem instead.

If your application has forms to edit string fields, you probably want to strip the entered values (remove whitespace from beginning and end). The reason is that your users will copy + paste values from unholy places (websites, Microsoft Office) and end up having trailing whitespace in most of their records.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Because browsers ignore whitespace, no one will usually notice this until you get the weirdest bug reports (e.g. two seemingly equal records are not, or multiple records for "unique" values).

Use the attached trait in your model to have it automatically strip all :string fields before validation:

class Organisation < ActiveRecord::Base
  validates_presence_of :name, :city, :phone, :website, ....
  does 'strip_string_fields'
end

Attributes of other types (including :text) are not stripped.

Stripping whitespace from existing records

If you have existing data that needs to be cleaned, do it in a migration, using MySQL's TRIM function:

class StripWhitespaceFromOrganisation < ActiveRecord::Migration
  def change
    update 'UPDATE organisations SET name = TRIM(name), city = TRIM(city), ...'
  end
end
Posted by Henning Koch to makandra dev (2012-10-18 17:21)