Skip to content

Migrating existing user records

Jeremy Lynch edited this page Dec 29, 2016 · 4 revisions

Before you remove the email column you can use this method to migrate your emails from the user to the emails table:

# models/user.rb
def update_emails
  # fetch the email attribute directly from the table
  existing_email = self.read_attribute_before_type_cast('email')
  if email == nil && existing_email != ''
    email = Email.new(email: existing_email, user: self, primary: true)
    email.skip_confirmation!
    email.save
    if email.errors.present?
      return errors
    end
    logger.info 'Email Updated!'
  else
    logger.info 'Email already exists or no email saved on record'
  end
end

In Rails console:

User.find_each(&:update_emails)

After you have migrated all emails you can remove the email column:

rails g migration remove_email_from_users email:string
rake db:migrate
Clone this wiki locally