Making a change to the rails database via a simple rake task

So you’ve made a change to the database. Will things still work with your existing code? Perhaps not. How then are you going to handle it?

You have some options:

(i) change the existing production database - all records to ensure things work. You can do this with a rake task. If you have a very large database, then you need to make sure that your migrations and/or rake tasks are efficient, otherwise they could take a very long time. And you will also have to handle situations where migrations fail half-way in between (for whatever reason). In addition, you will want to make sure that your app can handle traffic WHILE the database is undergoing this migration. There are a lot of moving parts here, and considerable knowledge and discernment is required in order to handle large scale migrations.

If you are developing a basic app with a very small amount of records, nothing beats the ease and simplicity of a rake task.

# Not efficient, but does the job
namespace :db do
  desc "Task: adds secure tokens to empty conversations"
  task add_secure_tokens_to_empty_conversations: :environment  do
    conversations = Conversation.where(token: nil).or(Conversation.where(token: ""))

    conversations.find_each(batch_size: 100) do |c|
      c.token = Conversation.generate_unique_secure_token
      c.save
    end
  end
end

Written on June 1, 2020