/ rails

Creating tables and problems with primary key in Rails

If you run into the following error when running a migration
in your legacy Rails app with MySQL 5.7 or above

rake aborted!
"Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL:"

the fix is by monkey patching the MySQL Adapter using the following code.

# lib/patches/abastract_mysql_adapter.rb
class ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
    NATIVE_DATABASE_TYPES[:primary_key] = 'int(11) auto_increment PRIMARY KEY'

and then require it from your environment.rb

require File.expand_path('../../lib/patches/abstract_mysql_adapter', __FILE__)

This issue is fixed in the latest version of Rails, but your legacy apps would need to be patched manually.

If you are interested in learning more about change that caused this issue, you can refer this link

Manu S Ajith

Manu S Ajith

Tech Entrepreneur, dating Elixir, in long-term ❤️ w/ Ruby, had multiple one night stands w/ Go. Into functional paradigms DDD/CQRS/EventSourcing architecture these days. @manusajith on the interwebs

Read More