1

I've just created a migration in rails to add a column to an existing table. Below is sample codes

class AddShortInfoToDepartment < ActiveRecord::Migration
  def self.up
    add_column :departments, :short_info, :string
  end

  def self.down
    remove_column :departments, :short_info, :string
  end
end

Beforehand, I've created a task file to seed the column.

namespace :db do
  namespace :seed do
    desc "seed short_info into table departments"
    task department_short_info: :environment do
      short_infos = [
        "Management and Administration",
        "Financial",
        "Clinical",
        "Clinical Support",
        "Patient Diet and Ration Management",
        "Health Record Management"
      ]

      Department.all.each_with_index do |department, index|
        department.update(short_info: short_infos[index])
      end

    end
  end
end

then I call the task in the migration file by adding a line:

class AddShortInfoToDepartment < ActiveRecord::Migration
  def self.up
    add_column :departments, :short_info, :string

    # seeding column short_info using rake task
    Rake::Task['db:seed:department_short_info'].invoke
  end

  def self.down
    remove_column :departments, :short_info, :string
  end
end

and finally, I ran the migration

rake db:migrate

There was no error in both during adding new column and during running rake task.

But, when I checked using console after migration done, the column "short_info" in the table has no data and returns nil.

To make sure that the rake task does it's work as intended, I ran the task using rake db:seed:department_short_info and it was successful and the column was seeded.

Is there a step that I missed or any command that I should run first before I run the migration?

3
  • Did you migrate before adding the task invocation, and then trying to migrate again? if so, you need to rollback the migration first, then do it again. Commented Mar 5, 2018 at 5:25
  • And you can replace update with update! to check if there's any validation error happens. Commented Mar 5, 2018 at 5:31
  • Yes @MoamenNaanou i did. This is just a sample coding to post here. The actual coding is more completed just like you suggest. Commented Mar 5, 2018 at 6:25

1 Answer 1

2

If I remember correctly, when you want to do a migration AND execute a seed task inside it, you have to execute #reset_column_information on the models you are going to use, in your case

Department.reset_column_information

That being said, beware of these kind of things since it can slow down a lot of your push in production depending on your dataset size.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.