Rails 4 Migration: Mysql2::Error: Data too long for column 'xxxx'

tzzzoz picture tzzzoz · Jun 19, 2014 · Viewed 9.8k times · Source

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 limit fo string for the column "name".

Then, in console:

 user = User.new(name:"1234567890",email:"[email protected]")
 user.save!

It raised the error:

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', '[email protected]', '1234567890', '2014-06-19 15:08:15')

But, when I switched to rails 3.

I found it truncated the string "1234567890" automatically, and inserted "123456" into database without error.

Is there anything about this has been removed in rails 4?

Should I add some truncate functions in the model by myself? Thanks!

Answer

James Mason picture James Mason · Jun 19, 2014

What you're seeing is a difference in MySQL, not Rails. By default, MySQL will truncate data that's too long rather than throwing an error. If you set MySQL to strict mode, it will throw errors instead of silently truncating data.

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

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

before_save :truncate_username
def truncate_username
  self.username = username.slice(0, 6)
end