PRIMARY KEY issue with creating tables in Rails using rake db:migrate command with mysql

后端 未结 5 1219
余生分开走
余生分开走 2020-12-31 00:38

My version of rails is 4.0.0, my version of mysql is Ver 14.14 Distrib 5.7.9, for Win64 (x86_64). I am operating of an older version of rails as I was getting some clashes w

相关标签:
5条回答
  • 2020-12-31 00:57

    I solved this problem with a Rails app on JRuby I'm working on by upgrading the mysql-adapter.

    I was using the gem activerecord-jdbcmysql-adapter v1.3.14 and upgraded to v1.3.21

    Check your jdbc adapter version before monkey patching a solution.

    0 讨论(0)
  • 2020-12-31 00:58

    Did not have luck with the solutions above (My env: Rails 3.0.20, MySQL 5.7.13, Ruby 1.9.3p551). Was able to get around it by overwriting the ActiveRecord::ConnectionAdapters::ColumnDefinition class. See below:

    class ActiveRecord::ConnectionAdapters::ColumnDefinition
      def sql_type
        type.to_sym == :primary_key ? 'int(11) auto_increment PRIMARY KEY' : base.type_to_sql(type.to_sym, limit, precision, scale) rescue type
      end 
    end
    

    Stored this in config/initializers/column_definition.rb

    0 讨论(0)
  • 2020-12-31 00:59

    I had this problem too (mysql 5.7.17 and Rails 4.0.0). I fixed it by adding a file config/initializers/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
    

    and then, in my environment.rb file:

    require File.expand_path('../initializers/mysql2_adapter', __FILE__)
    
    0 讨论(0)
  • 2020-12-31 01:03

    Since MySQL 5.7.3 a primary key declared as NULL produces an error:

    Columns in a PRIMARY KEY must be NOT NULL, but if declared explicitly as NULL produced no error. Now an error occurs. For example, a statement such as CREATE TABLE t (i INT NULL PRIMARY KEY) is rejected. The same occurs for similar ALTER TABLE statements. (Bug #13995622, Bug #66987, Bug #15967545, Bug #16545198)

    But the create_table in your Rails version still wants a DEFAULT or NULL for the PRIMARY KEY. I have solved the issue by updating to a newer rails version.

    0 讨论(0)
  • 2020-12-31 01:15

    I too recently faced same issue.

    MySQL 5.7 no longer supports null default values for the primary key.

    By overriding the Native default for primary keys in MySql you can resolve your issue.

    In config/initializers/abstract_mysql_adapter.rb:

    class ActiveRecord::ConnectionAdapters::MysqlAdapter
      NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
    end
    

    For mysql2 it should be config/initializers/abstract_mysql2_adapter.rb:

    class ActiveRecord::ConnectionAdapters::Mysql2Adapter
      NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
    end
    
    0 讨论(0)
提交回复
热议问题