Posted 5 months ago. Visible to the public. Repeats.

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.


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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Henning Koch
Last edit:
4 months ago
by Henning Koch
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 makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more