Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store long text to MySql DB using Rails?

I am trying to store a long text (in my case a raw rss feed, but could just as well be a long blog post or similar) to a MySql database.

I have a migration with:

change_column :contents, :description, :longtext

But this gives a schema.rb with:

t.text     "description",       :limit => 2147483647

When the limit should in fact have been set to 4294967295.

Why does Rails impose an upper limit which is half of what should be possible?

like image 809
Magne Avatar asked Jul 26 '11 13:07

Magne


1 Answers

I don't know if rails supported :longtext officially in previous versions, but in the current version according to rails documentation, :longtext is in fact not specified as legal datatype. I think it's only a convenience of the mysql adapter that translates this to :text.

The correct way to do it is then:

change_column :contents, :description, :text, :limit => 4294967295

Keep it mind that the effective maximum size is less when using multi-byte characters.

Edit: Thinking a second about it and it makes sense that rails halves the size. Re-reading the mysql docs on this topic , they speak of effective size. I guess specifying 2147483647 could lead to an effective size of 4294967295 when filled with 2-byte UTF-8 characters. As UTF-8 is the default encoding in ruby 1.9 (at least on my machine), it's the only correct way to do it. I think?!

ruby-1.9.2-p136 :002 > "".encoding
=> #<Encoding:UTF-8> 
like image 61
Paul Schyska Avatar answered Oct 02 '22 06:10

Paul Schyska