简体   繁体   中英

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?

How are you expecting Rails to know which Product B(s) belong to which record of RegionA? If you can define this behaviour programatically, you can do something like this:

ProductB.all.map { |p| p.region_a = region_a }

Where region_a is a defined region that you've found. This can also be placed within your migration.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM