Migrating DATA - not just schema, Rails

后端 未结 3 1686
忘掉有多难
忘掉有多难 2020-12-31 07:16

Sometimes, data migrations are required. As time passes, code changes and migrations using your domain model are no longer valid and migrations fail. What a

相关标签:
3条回答
  • 2020-12-31 07:48

    Some times 'migrating data' could not be performed as a part of schema migration, like discussed above. Sometimes 'migrating data' means 'fix historical data inconstancies' or 'update your Solr/Elasticsearch' index, so its a complex task. For these kind of tasks, check out this gem https://github.com/OffgridElectric/rails-data-migrations

    This gem was designed to decouple Rails schema migrations from data migrations, so it wont cause downtimes at deploy time and make it easy to manage in overall

    0 讨论(0)
  • 2020-12-31 07:52

    This is a perfect example of the Using Models in Your Migrations

    class ChangeFromPartnerAppliedToAppliedAt < ActiveRecord::Migration
      class User < ActiveRecord::Base
      end
    
      def up
        User.all.each do |user|
          user.applied_at = user.partner_application_at
          user.save
       end
     end
    

    Edited after Mischa's comment

    class ChangeFromPartnerAppliedToAppliedAt < ActiveRecord::Migration
      class User < ActiveRecord::Base
      end
    
      def up
        User.update_all('applied_at = partner_application_at')
      end
     end
    
    0 讨论(0)
  • 2020-12-31 08:02

    Best practice is: don't use models in migrations. Migrations change the way AR maps, so do not use them at all. Do it all with SQL. This way it will always work.

    This:

    User.all.each do |user|
      user.applied_at = user.partner_application_at
      user.save
    end
    

    I would do like this

    update "UPDATE users SET applied_at=partner_application_at"
    
    0 讨论(0)
提交回复
热议问题