Read more

ActiveRecord: String and text fields should always validate their length

Henning Koch
July 13, 2020Software engineer at makandra GmbH

If you have a :string or :text field, you should pair it with a model validation that restricts its length.

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

There are two motivations for this:

  • In modern Rails, database types :string and :text no longer have a relevant size limit. Without a validation a malicious user can quickly exhaust the hard drive of your database server.
  • In legacy Rails (or database schemas migrated from legacy Rails), database types :string and :text had a database-side length constraint. When the user enters a longer string, the ActiveRecord validation will pass and then crash when making the SQL statement. The user sees an error box ("Something went wrong") instead of a validation error.

Example

We have a User model that has an email field as :string and a multi-line profile text (profile) as :text. We limit the length of both fields in the model:

class User < ApplicationRecord
  validates :email, presence: true, length: { maximum: 100 }
  validates :profile, length: { maximum: 20_000 }
end  

See also

Posted by Henning Koch to makandra dev (2020-07-13 10:06)