Reputation: 155
I ended up in a situation where I have a relatively large table, and I need to add a new column to it. Sounds easy enough? Well, there is a catch - I also need to fill that new column with data based on data already present, but I have no idea how to automate this process.
I have columns 'title' and 'title_de', and new column is 'lang'. New column should contain either 'de' or 'eng' depending on if 'title' is blank or not (blank 'title' means it's 'de', non blank means it's 'eng').
How to tackle this?
Upvotes: 0
Views: 23
Reputation: 9491
You will want to do something like this:
class AddColumnToItems < ActiveRecord::Migration[5.0]
def change
add_column :items, :lang, :string
ActiveRecord::Base.transaction do
Item.all.each do |item|
item.lang = "de"
item.lang = "eng" unless item.title.blank?
item.save
end
end
end
end
Then:
rake db:migrate
I hope that solves your problem!
Upvotes: 1