Rails 4 Migration: Mysql2 :: Error: too large data for column "xxxx"

Here is my schema.rb

create_table "users", force: true do |t| t.string "name", limit: 6 t.string "email" t.datetime "created_at" t.datetime "updated_at" end 

I set the fo limit for the "name" column.

Then in the console:

  user = User.new(name:"1234567890",email:" username@gmail.com ") user.save! 

An error occurred:

 ActiveRecord::StatementInvalid: Mysql2::Error: Data too long for column 'name' at row 1: INSERT INTO `users` (`created_at`, `email`, `name`, `updated_at`) VALUES ('2014-06-19 15:08:15', ' username@gmail.com ', '1234567890', '2014-06-19 15:08:15') 

But when I switched to rails 3.

I found that it automatically shortened the string " 1234567890 " and inserted " 123456 " into the database without errors.

Has anything been removed about this in rails 4?

Should I add some truncation functions to the model myself? Thanks!

+7
ruby-on-rails ruby-on-rails-4 rails-migrations
source share
2 answers

What you see is the difference in MySQL, not Rails. By default, MySQL will truncate data that takes too long, and not throw an error. If you set MySQL to strict mode, it will generate errors instead of silent data truncations.

With version 4, by default, Rails mode includes strict mode . That's why you see different behavior with Rails 3. This is the behavior that you probably want. Silently trimming data is almost always bad and can lead to very confusing behavior for users.

If you really want to truncate the data, you can turn off strict mode or use the before filter:

 before_save :truncate_username def truncate_username self.username = username.slice(0, 6) end 
+16
source share

I came across this article , which was written just a few days ago.

Of primary interest is the following:

... Recently, I upgraded from rails 3.2 to rails 4.0. They implemented a significant change with ActiveRecords that I can’t find any mention of anywhere except the source and change log.

  • Default connections
  • mysql and mysql2 set SQL_MODE=STRICT_ALL_TABLES to avoid data loss without data loss. This can be disabled by specifying strict: false in your database.yml .

It would seem that this explains why you stopped receiving the error when returning to Rails 3. You can see this in the settings of the MySQL connection module , and it looks like it was added back in May 2012 for the candidate version 4.1.2 ( if I read the tags).

This person solved his problem with the [fixing] code to either have the correct field lengths or manually trim the data ...

In your case, you can solve your problem in Rails 4 by simply adding strict: false to your database.yml . If you want to customize how the data is truncated, I agree with JKen13579's suggestion on the before_save . Otherwise, from what I see, it seems to truncate the right characters, so if that is enough, you can probably get away with the default truncation behavior.

+7
source share

All Articles