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?
updatewithupdate!to check if there's any validation error happens.