Define the length of varchar for MySQL in rails

Sachin Prasad picture Sachin Prasad · Dec 21, 2012 · Viewed 13.3k times · Source

I want to define the size of the varchar in rails for example name varchar(20), age varchar(6),through git-bash in process of generating the model.

I searched on the stack but couldn't find any answer.

Answer

tadman picture tadman · Dec 21, 2012

There's a number of options when creating columns that are documented for the column method. They also apply to add_column when doing subsequent modifications.

The most concise way to make a more limited column is:

t.string :name, :limit => 20
t.string :age, :limit => 6

As a note, it's highly unusual to impose limits like this in your database and a better solution is to limit on the model using validates. For example:

validates :name,
  :presence => true,
  :length => { :maximum => 20 }

MySQL has a tendency to truncate values that are too long without telling you, so not having a length limit will eventually lead to lost data, especially with such a short length.

Remember that VARCHAR columns in the database are variable length, so there's no storage advantage to a ten character value in a VARCHAR(255) versus a VARCHAR(20).