Rails 3: Data Transfer

My Rails 3 has a user model and a profile model. User has_one Profile.

The profile currently has the attributes first_name and last_name . Although I'm not sure why you might want to change them, I initially assumed that they should be mutable, and so I put them in the profile model instead of the user model.

However, as the application evolved, I found that I really need the username and surname to not change, and that they really need them to be part of the User model instead of the profile model.

So, I was wondering if you can write a migration that:

  • Add the first_name and last_name to the user model.
  • Take the existing first_name and last_name value for this user from the associated profile entry and copy it into the user model.
  • Remove the first_name and last_name from the profile model as they are no longer needed.

So can this be done? Could you set an example? And, most importantly, are there any issues I should be aware of? I would like to apply this change to a production application, so it is important that I do not lose data when I make this change.

Thanks!

+4
source share
3 answers

Of course, very easy. Put this in the migration:

  add_column(:users, :last_name, :string) add_column(:users, :first_name, :string) User.reset_column_information User.all.each do |u| u.last_name = u.profile.try(:last_name) u.first_name = u.profile.try(:first_name) u.save end remove_column(:profiles, :first_name) remove_column(:profiles, :last_name) 

I used try () to mitigate the possibility of a missing profile. It does not check for errors during the save operation, so consider this if you think it is necessary. Also, as always, back up the database dump before starting it. :)

+13
source

I think this is the gem you need:

https://github.com/btelles/legacy_migrations

+2
source

I recently created a gem that solves the problem of recording migration data in migrations - https://github.com/ka8725/migration_data .

+1
source

All Articles