Search code examples
ruby-on-railsrails-migrations

Best practise to populate somedata in a existing database in rails


Problem statement:

Let's say I created a new column column_1 in a table table_1 through rails migration. And now I want to populate the data into column_1 doing some computation but it's a one time task.

Approaches:

Is it preferred to do it through migration. or should I add it in seeds and then populate it and remove it back again

or is there any other best practise.


Solution

  • Even though there are different approaches, it is better to do that in in Rake or Migrations but not seed.

    Rake tasks:

    Rake tasks are generally preferred to do maintenance or data migration jobs over a collection of data.

    Example of rake:

    lib/tasks/addData.rake

      desc "TODO"
      task :my_task1 => :environment do
        User.update_all(status: 'active')
      end
    

    Example of doing it in migration:

    If you add status field to user:

    class AddStatusToUser < ActiveRecord::Migration
      def up
        add_column :users, :status, :string
        User.update_all(status: 'active')
      end
    
      def down
        remove_column :users, :status
      end
    end
    

    Why Not seeds:

    Seeds are generally like database Dump, seed files are used to fill the data into Database for the first time when the application is started. So that the application is kickstarted with different data.

    Examples are Application settings, Application Configurations, Admin users etc.