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.
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.
Always specify a length to any text-based datatype such as NVARCHAR or VARCHAR .
VARCHAR(255) stores 255 characters, which may be more than 255 bytes.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With