ActiveRecord: String and text fields should always validate their length

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

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

Henning Koch Over 3 years ago