0

I'm new to RoR, and need some help on migration. I have an existing database containing a "date" column in a mysql database. I need to store them into 3 separate integer fields (year, month, date) (don't ask me why, because my clients are idiots)... and need to migrate the existing column into the new columns (The existing database already contain data). I'm just wondering how could I do that in migration?

Thank you

1 Answer 1

0

After some digging... solved it. Migration is not the preferred way of doing this, rake task should be used.

First, generate the new columns using migrations, than add the new attr_accessible in the model.

To generate a rake task, follow http://railsguides.net/how-to-generate-rake-task/ link.

And use the following code, assuming the model containing the date column is called Visit

namespace :visit_date_migration do
  desc "Migrate visit date into 3 integer columns for year/month/date"
  task :migrate_date => :environment do
      Visit.all.each do |visit|
          unless visit.visit_date.nil? || visit.visit_date == 0
              year = visit.visit_date.year
              month = visit.visit_date.month
              day = visit.visit_date.day
              visit.visit_date_year=year
              visit.visit_date_month=month
              visit.visit_date_date=day
              visit.save!
          end
      end
  end
end

And run the rake task like a normal task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.