Search code examples
sqlruby-on-railspostgresqlrails-migrations

Create first_name and last_name from full_name in a Rails migration


I have a table (People) with a full name column, but want to split it into a first name (and initial if it exists) column and last name column.

It's a PostgreSQL database FWIW. I'm at the point of creating the columns, so it can all be done in the migration if that's possible. The names all fit the old standard American style, that is, no compound names or hyphens. No periods after the initials and some of the first names are initials only. This will be a one shot change, and then any new entries will be First and Last names in their separate fields. The full name field will be dropped.

Thanks for any help


Solution

  • You can do it like this in single migration

    create two new columns

    add_column :people, :first_name, :string
    add_column :people, :last_name, :string
    

    then

      full_names = People.all.map(&:full_name)
    

    it return new array of full_name ['full_name','full_name1',..etc]

    and then

    full_names.each do |n| People.create(first_name:n.split('_')[0],
                                         last_name:n.split('_')[1])
    end 
    

    and remove full_name column

    remove_column :people, :full_name 
    

    Clumsy solution but should works