All threads / Using migrations to migrate data from one table into another

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Using migrations to migrate data from one table into another

Shairyar Baig asked in Rails

I have two models user and account linked with each other as following

account.rb
belongs_to :user

user.rb
has_many :accounts

I want to move the data from column name in users table into column name in accounts table

I think the following should do the job but my question is if there is a better way of doing this inside a migration file considering if there are thousands of records?

Account.find_each do |account|
      if account.user.present?
        account.update_columns(name: account.user.name, xyz: account.user.xyz)
      end
end

Note: Once this migration will run I will remove the column user_id in accounts table removing the relationship between the two modals.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,399+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.