Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define the length of varchar for MySQL in rails

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.

like image 253
Sachin Prasad Avatar asked Dec 21 '12 06:12

Sachin Prasad


People also ask

How long does VARCHAR take MySQL?

Varchar in MySQL is a data type used for storing text whose length can have a maximum of 65535 characters. The varchar columns in the table are of variable length string that can hold either numeric or character or both. This data type is capable of storing only 255 characters before version 5.0.

Should I specify length of VARCHAR?

Always specify a length to any text-based datatype such as NVARCHAR or VARCHAR .

What is the size of VARCHAR 255?

VARCHAR(255) stores 255 characters, which may be more than 255 bytes.

What is VARCHAR maximum length?

The size of the maximum size (m) parameter of a VARCHAR column can range from 1 to 255 bytes. If you are placing an index on a VARCHAR column, the maximum size is 254 bytes. You can store character strings that are shorter, but not longer, than the m value that you specify.


1 Answers

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).

like image 81
tadman Avatar answered Oct 30 '22 17:10

tadman