Rietta
Rietta: Web Apps Where Security Matters
You are reading The Rietta Blog, a publication about the web since 2005.

Rails: Set Max Length on Fields

I originally started drafting this post on January 14, 2012, but it sat unpublished since then. Its fun to look back at ones journey, 1743 days ago. In 2012, I was relatively new to the Ruby on Rails platform after having worked in PHP and SQL for years, as well as a little .NET. The platform has been a good choice that I enjoy working with still to this day. I was working in Rails 3 at the time and had completed at least three client websites in Rails in 2011.

Anyway, let’s take a look at the little lesson that I had started to write about over 4 years ago.

How to Handle Maximum Lengths for User Supplied Input

Stop annoying users by appearing to allow more text in a field than supported!

The default length of a string in an ActiveRecord model is 255 characters. By default the text_field helper will allow the user to enter more. As a user, one is incorrectly to think that he or she can enter more text than is allowed and it is silently truncated by the web app. Stop it, seriously.

Do it by two easy steps:

  1. Set the maxlength and size attributes on your one-line text fields.
  2. Validate the length of the text fields in your model.

In the View:

1
  <%= f.text_field :first_name, maxlength: 255, size: 30 %>

In the Model:

1
2
3
4
5
  validates :first_name,
    presence: true,
    length: {maximum: 255},
    on: :create,
    allow_nil: false

Conclusion

Even today in 2016, many Rails developers leave maximum length validation out of their Rails models. This is a mistake. If you are using PostgreSQL, then validating that a string is no more than 255 is even more important because a string that is longer will cause the model to be reported as valid and yet PostgreSQL will raise an exception on save. This will lead to data loss and the dreaded “Something Went Wrong” 500 error page for your users unless you handle the length validation properly.

About Frank Rietta

Frank Rietta's photo

Frank Rietta is specialized in working with startups, new Internet businesses, and in developing with the Ruby on Rails platform to build scalable businesses. He is a computer scientist with a Masters in Information Security from the College of Computing at the Georgia Institute of Technology. He teaches about security topics and is a contributor to the security chapter of the 7th edition of the "Fundamentals of Database Systems" textbook published by Addison-Wesley.