A :limit of Rails' Migrations

Migrations in Ruby on Rails use the ":limit" symbol to set the maximum length of the underlying field's data type. Take for example, the following example migration:
create_table :things do |t|
          t.string :name, :limit => 32
          t.string :description
By default, Rails will create :description as data type "varchar(255)" and :name as "varchar(32)" in a MySQL database. But did you know you can set :limit to be greater than 255? For whatever reason, many of us have gained the impression that 255 is the longest :string can be, but that just isn't the case. If I wanted the :description field in the example above to be greater than 255, I could just define it as follows:
t.string :description, :limit => 1024
In fact, strings (i.e. varchars) in MySQL can hold up to 65,535 bytes of data. The opinionated nature of  Ruby on Rails is a great asset in most instances, but we have to be careful not to let its opinions :limit us. Note: I'm pretty sure Rails sets the default limit of strings to be 255 for two reasons: 1) cross database compatability, and 2) MySQL's InnoDB (utf-8) engine can't index varchar fields exceeding 255 characters.

Further Reading

Established 2005 · Databasically © 2016