Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead

前端 未结 4 1751
我寻月下人不归
我寻月下人不归 2021-02-01 09:38

I have created a demo application in rails 3.2.9 and ruby versiion 2.0.0 . After scaffolding Blog model I am trying to migrate it, but having following

相关标签:
4条回答
  • 2021-02-01 09:54

    config/initializers/abstract_mysql2_adapter.rb

    require 'active_record/connection_adapters/mysql2_adapter'
    
    class ActiveRecord::ConnectionAdapters::Mysql2Adapter
      NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
    end
    
    0 讨论(0)
  • 2021-02-01 10:04

    I had this problem too (mysql 0.3.21 and Rails 3.2.22.5). I fixed it by adding a file in my application config/initializers/mysql2_adapter.rb (as there was no such file before)

    Added below contents,

    require 'active_record/connection_adapters/mysql2_adapter' class ActiveRecord::ConnectionAdapters::Mysql2Adapter NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY" end

    and then, in my environment.rb file added below contents,

    require File.expand_path('../initializers/mysql2_adapter', FILE)

    And it worked.

    0 讨论(0)
  • 2021-02-01 10:07

    In this line id int(11) DEFAULT NULL auto_increment PRIMARY KEY you are creating a primary key (which can never be null), with the default value NULL. In your migration file (or schema.rb) you should make sure the DEFAULT NULL part is removed.

    0 讨论(0)
  • 2021-02-01 10:11

    This error occurred when not null is defined with primary key column.

    Even if you defined any composite key, then those column definition does not contains the not null criteria.

    Search for those column, remove the not null criteria, this is one of the solution to remove the error.

    0 讨论(0)
提交回复
热议问题