views:

38

answers:

2

Is there any point to specifying a limit option on string in migrations...

class CreateAccounts < ActiveRecord::Migration
  def self.up
    create_table :accounts do |t|
      t.string :name, :limit => 64
    end
  end
end

Should this be applied to all strings in the DB? What's the significance?

A: 

The first thing that comes to mind - when you have millions of accounts, that limit will actually affect the size of your DB a lot.

neutrino
+5  A: 

Strings are usually 255 characters length but not all databases treat the string field in the same way. For instance, PostgreSQL can create string column of different sizes.

There are at least 2 very good reasons to specify the value of the string field:

  1. cross-database compatibility
  2. database performance

If you need a string column to store the country code that is 2 chr length, why you want the database to reserve additional 253 characters for... nothing?

Also note you should always validate the length of the field value in your model. If you try to create a record with a name that exceeds your maximum length:

  1. SQLIte3 will silently trim the value
  2. MySQL will silently trim the value
  3. PostgreSQL will raise an exception

So, always validates_length_of your attribute.

Simone Carletti