Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move a column (with contents) to another table in a Rails migration?

I need to move some columns from one existing table to another. How do I do it using a rails migration?

class AddPropertyToUser < ActiveRecord::Migration   def self.up     add_column :users, :someprop, :string     remove_column :profiles, :someprop   end    def self.down     add_column :profiles, :someprop, :string     remove_column :users, :someprop   end end 

The above just creates the new columns, but values are left empty...

I want to avoid logging in to the database to manually update the tables.

If there is a way to move column values programmatically, what are the performance characteristics? Would it do row-by-row, or is there a way to update in bulk?

like image 697
Eero Avatar asked May 26 '11 08:05

Eero


People also ask

How do I move a specific table in rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

What is data migration in Rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.


1 Answers

I ended up using this migration (tested, it works, and rolls back successfully):

class AddPropertyToUser < ActiveRecord::Migration   def self.up     add_column :users, :someprop, :string     execute "UPDATE users u, profiles p SET u.someprop = p.someprop WHERE u.id = p.user_id"     remove_column :profiles, :someprop   end    def self.down     add_column :profiles, :someprop, :string     execute "UPDATE profiles p, users u SET p.someprop = u.someprop WHERE p.user_id = u.id"     remove_column :users, :someprop   end end 

I like it because it avoids the row-by-row updates on a large database.

like image 187
Eero Avatar answered Oct 04 '22 02:10

Eero