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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)