In the previous chapter, we reset the counter cache via the console. Sometimes, you may need a larger script to reset your database or handle multiple conditions and update a database value. For example, if you need to update a column for all records that meet specific criteria, a data migration script would be required. Here, we can utilize rake tasks to achieve this. These rake tasks only need to run once, so they are called one_timer
rake tasks. Let's consider a scenario for writing a rake task. Suppose you have a Rails app where users can post articles, with each article's view count stored in the views_count
column. Initially, view counts were not tracked separately, but now you want to set a default count based on specific conditions:
- Articles created over a year ago should start with a view count of 100.
- Articles created within the last year should start with a view count of 10.
To create the one_timer
rake task file, run the following command in your terminal:
Now, you can define all your one-time Rake tasks in this file by adding each task under one_timer
namespace.
You can now run these tasks in the terminal with the following command:
One challenge with one-timer Rake tasks is that developers may occasionally forget to run these tasks in the production environment, which can lead to unexpected behavior in the application. To automate this process, we can use the data_migrate gem, allowing us to run data migrations alongside schema migrations as we saw in this chapter.
This is a theoretical chapter. There is nothing to commit in here. If you have made some changes to the project, clean them up by executing the
following command.