Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge columns in a rails table?

I have a rails table of users, with columns first_name and last_name etc. How do i merge these two together? Or how do i create a new column called name and add data from these two columns? Basically i need a column called name which is the concatenation of the first_name and last_name.

like image 711
ShivamD Avatar asked Mar 08 '13 05:03

ShivamD


2 Answers

As Richard Brown has answered, you should create a migration if you want to save the concatenated string to the database.

rails g migration add_fullname_to_users fullname

then run an sql inside the generated migration to update all records

# mysql
User.update_all('fullname = CONCAT(first_name, " ", last_name)')

# postgre
User.update_all("fullname = (first_name || ' ' || last_name)")

But I'd suggest you just keep your current setup and just create a method called fullname in your model

# user.rb
def fullname
  "{first_name} #{last_name}"
end

which is better since you have access to first_name and last_name

like image 110
jvnill Avatar answered Nov 14 '22 10:11

jvnill


If you want to make sure you can rollback, you can do something like this in your migration file.

  def up
    add_column :your_table, :name, :string 

    YourClass.all.each do |person|
      person.update_attributes! :name => person.first_name + " " + person.last_name
    end

    remove_column :your_table, :first_name
    remove_column :your_table, :last_name  
  end

And your down method for the roll back:

  def down
    add_column :your_table, :first_name, :string
    add_column :your_table, :last_name, :string

    YourClass.all.each do |person|
      person.update_attributes! :first_name => person.name.match(/\w+/)[0]
      person.update_attributes! :last_name => person.name.match(/\w+/)[1]
    end

    remove_column :your_table, :name
  end
like image 22
thomasstephn Avatar answered Nov 14 '22 09:11

thomasstephn