Reputation: 14798
I have a column name
in database which holds strings like CVM™
what I want to do is to split it so everything after ampersand goes into a different column and everything before the string stays where it was. The final result should put ™
into a column called abbr
and save CVM
into name
column.
Upvotes: 1
Views: 1389
Reputation: 4904
Must this be done Rails level? You can also do this with just Postgres with split_part
function. I assume you're working with users
table:
ALTER TABLE users ADD COLUMN abbr VARCHAR;
UPDATE users
SET name = SPLIT_PART(name, '™', 1),
abbr = '™' || SPLIT_PART(name, '™', 2);
You can also bake these queries into a Rake task if needed.
Update: Opps I assumed you were using Postgres. But other languages should have similar method that you can use.
Upvotes: 0
Reputation: 2080
Create a rake task file
lib/tasks/split_name.rake
Then paste in the following, and change "TableName" to your actual table name.
task :split_name => :environment do
TableName.all.each do |r|
a = r.name.split("&") #assuming exact same string format, and not null
r.update_attribute(:name, a[0])
r.update_attribute(:abbr, '&' + a[1])
end
end
Then run it as such
rake split_name
Upvotes: 1