rails3 bigint primary key

前端 未结 6 1557
小鲜肉
小鲜肉 2020-12-11 03:53

I would like to create a bigint (or string or whatever that is not int) typed primary key field under Rails 3.

I have a given

6条回答
  •  天命终不由人
    2020-12-11 04:00

    skalogirou's answer is good but the change will not be reflected in schema.rb. So the tasks like db:schema:load and db:test:clone will not create identical DB structure.

    The required workaround is to enhance db:schema:load and db:test:clone rake tasks as described here: http://www.lshift.net/blog/2013/09/30/changing-the-primary-key-type-in-ruby-on-rails-models/

    This is what I used based on that workaround:

    namespace :my_app do
      namespace :db do
        task :after_schema_load_and_db_test_clone => :environment do
        puts 'Changing primary key for :my_table'
        query = 'ALTER TABLE  CHANGE id id bigint DEFAULT NULL auto_increment'
        ActiveRecord::Base.connection.execute(query)
      end
    end
    
    
    Rake::Task['db:schema:load'].enhance do
      ::Rake::Task['my_app:db:after_schema_load_and_db_test_clone'].invoke
    end
    
    Rake::Task['db:test:clone'].enhance do
      ::Rake::Task['my_app:db:after_schema_load_and_db_test_clone'].invoke
    end
    

提交回复
热议问题