Posted 4 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.

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:

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

See also

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.

Owner of this card:

Avatar
Henning Koch
Last edit:
3 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