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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With