Search code examples
ruby-on-railsrails-migrations

How to populate ids from add_reference rails migration on existing model


I have 4 existing models say RegionA, RegionB, ProductA, and ProductB with definitions

class RegionA < ...
   has_many :product_as
   ...
end

class ProductA < ...
   belongs_to :region_a
   ...
end

class RegionB < ...
   has_many :product_bs
   ...
end

class ProductB < ...
   belongs_to :region_b
   ...
end

I can add an association between productB and regionA by running the migration generated by

rails g migration AddProductAToRegionBs producta:references

but the ids are not populated in the new columns. Given that there are millions of records, what is the best way to populate these ids in a way that won't force migrations to run for hours? Can I kick of a activejob from the migration, or is it best to run a manual script after deployment? What is the best approach here?


Solution

  • I ended up writing a script that ran the equivalent of the migrations in sidekiq to populate the associations before running the migrations in the first place. I then had a prepped db before the deploy and the transition was simple.