Add auto increment column in Postgres in Rails

class AddAutoIncrements < ActiveRecord::Migration
  def self.up
    add_column :designs, :custom_id, :integer
    execute <<-SQL
     CREATE SEQUENCE custom_id_seq START 1;
     ALTER SEQUENCE custom_id_seq OWNED BY designs.custom_id;
     ALTER TABLE designs ALTER COLUMN custom_id SET DEFAULT nextval('custom_id_seq');
    SQL
  end


  def self.down
    remove_column :designs, :custom_id
    execute <<-SQL
      DROP SEQUENCE custom_id_seq;
    SQL
  end


end
OR Added by Active record:
class AddAutoIncrements < ActiveRecord::Migration
 def self.up    
   add_column :users, :custom_id, :integer
  ActiveRecord::Base.connection.execute("CREATE SEQUENCE users_id_seq")
  ActiveRecord::Base.connection.execute("ALTER SEQUENCE users_id_seq OWNED BY users.id")
  ActiveRecord::Base.connection.execute("ALTER TABLE users ALTER COLUMN id SET DEFAULT nextval('users_id_seq')")   
    
   end
  end


  def self.down
    remove_column :users, :custom_id
    execute <<-SQL
      DROP SEQUENCE custom_id_seq;
    SQL
  end
end

Comments

Post a Comment

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Reading Excel Sheets using "Roo" gem in ruby on rails

Bootstrap Select Picker append add new item if search not exist

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails