Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails change column to mediumtext

I need to change a column from type TEXT to MEDIUMTEXT. As per this discussion: How to store long text to MySql DB using Rails?, I will need to specify a limit on size as half of the allowable range for that particular TEXT type in MySQL. However, what I am experiencing is that even by halving, I'm still getting the type that's one level above what I need. Does anyone have a better doc where this was documented or know why this is happening? Thanks!

like image 802
gtr32x Avatar asked Mar 12 '12 16:03

gtr32x


2 Answers

See this answer: 'Rails 3 Migration with longtext'

The reason why the limit values you're inputting are being ignored is due to how MySQL works. It has four text types, each with their own size limit:

  • TINYTEXT - 256 bytes
  • TEXT - 65,535 bytes
  • MEDIUMTEXT - 16,777,215 bytes
  • LONGTEXT - 4,294,967,295 bytes

A text column needs to be one of those four types. You can't specify a custom length for these types in MySQL.

So if you set a limit on a :text type column, Rails will automatically pick the smallest of those types that can accommodate that value, silently rounding up the limiting value you inputted to one of those four limits above.

Example:

t.text :example_text_field, limit: 20

will produce a TINYTEXT field with a limit of 256 bytes, whereas

t.text :example_text_field, limit: 16.megabytes - 1

will produce a MEDIUMTEXT field with a limit of 16,777,215 bytes.

Update

For the shake of the question: "I need to change a column"

change_column :example_table, :example_text_field, :text, limit: 16.megabytes - 1
like image 164
Stu Blair Avatar answered Nov 12 '22 21:11

Stu Blair


change_column :example_table, :example_text_field, :mediumtext

Example:

def change
   change_column :users, :bio, :mediumtext
end
like image 22
araslanov_e Avatar answered Nov 12 '22 19:11

araslanov_e