Sunday, 24 November 2024

Update ID with primary id

 create_table :apps do |t|

  t.references :company, foreign_key: true

  t.string :app_id

  t.string :app_secret

  t.boolean :status, default: false


  t.timestamps

end


Local : primary id updated

118 to 6

# There is no record of 6 id

ActiveRecord::Base.transaction do

  ActiveRecord::Base.connection.execute("ALTER TABLE apps DROP CONSTRAINT fk_rails_2701a89c0b;")

  company = Company.find(118)

  company.update!(id: 6)

  App.where(company_id: 118).update_all(company_id: 6)

  ActiveRecord::Base.connection.execute("ALTER TABLE apps ADD CONSTRAINT fk_rails_2701a89c0b FOREIGN KEY (company_id) REFERENCES companies(id);")

end


71 to 118


ActiveRecord::Base.transaction do

  ActiveRecord::Base.connection.execute("ALTER TABLE apps DROP CONSTRAINT fk_rails_2701a89c0b;")

  company = Company.find(71)

  company.update!(id: 118)

  App.where(company_id: 71).update_all(company_id: 118)

  ActiveRecord::Base.connection.execute("ALTER TABLE apps ADD CONSTRAINT fk_rails_2701a89c0b FOREIGN KEY (company_id) REFERENCES companies(id);")

end

No comments:

Post a Comment