After a couple of hours working through various sites I came up with three migrations:
timestamp_add_first_last_to_users.rb
class AddFirstLastToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
add_column :users, :first_name, :string
add_column :users, :middle_name, :string
add_column :users, :last_name, :string
end
end
def self.down
remove_column :users, :first_name
remove_column :users, :middle_name
remove_column :users, :last_name
end
end
timestamp_update_names_to_users
class UpdateNamesToUsers < ActiveRecord::Migration
def up
User.all.each do |user|
na=user.name.split(" ")
nc=na.size
user.first_name=na[0]
user.last_name=na.last if na.size>1
user.middle_name= na[1..na.size-1].join(" ") if na.size>2
user.save!
end
end
def down
User.all.each do |user|
user.name = [user.first_name, user.middle_name, user.last_name].compact.join(" ")
user.save!
end
end
end
class RemoveNameFromUsers < ActiveRecord::Migration
def up
remove_column :users, :name, :string
end
def down
add_column :users, :name, :string
end
end
This works, but is probably not the best solution.
If you have an easier way, please feel free to let me know.
No comments:
Post a Comment