I'm using Rails 4.2.5, and I'd like to update existing records with a csv file with two fields: id,category. Where if the category field is blank, it defaults to misc.
Here's an example csv file:
id,category
123-123-123,0
123-123-124,1
123-123-125,
123-123-126,2
So, I've created some tasks, update_item_categories
, and set_item_categories
:
# lib/tasks/update_item_categories.rake
require 'csv'
namespace :db do
task :update_item_categories => :environment do
categories = ['misc', 'food', 'drink']
CSV.foreach('public/update/item_categories.csv', headers: true) do |row|
row_hash = row.to_hash
category = categories[row_hash['category'].to_i]
unless Item.where(id: row_hash['id']).empty?
item = Item.find(row_hash['id'])
item.update_attributes(
:category => category
)
item.save!
end
end
task :set_item_categories => :environment do
Item.where(category: nil).each do |item|
item.update_attributes(category: 'misc')
item.save!
end
end
end
I will definitely appreciate any advice on how this could be better written, and also whether this is even a good way to go about solving this problem.