Posted almost 5 years ago. Visible to the public.

Automatically strip all string fields of an ActiveRecord

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.

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:

Copy
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:

Copy
class StripWhitespaceFromOrganisation < ActiveRecord::Migration def change update 'UPDATE organisations SET name = TRIM(name), city = TRIM(city), ...' end end

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Author of this card:

Avatar
Henning Koch
Attachments:
strip_string_fields_trait.rb
Keywords:
columns, trip
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandropedia