[RUBY] [Rails] Implement rake task

What is a rake task?

This function executes the processing described in the file from the command line. It is used for various purposes such as changing the status according to the user's attributes, importing CSV data, sending an email to the user at any time, and so on.

Basic usage

Generate task file

$ rails g task qiita_task

Describe the process you want to execute

namespace :qiita_task do
  desc 'hello world'
  task :hw do
    puts 'Hello World'


$ rake qiita_task:hw


When the process to connect to DB is included in the task

When connecting to DB, write ╩╗environment` as follows

namespace :qiita_task do
  desc 'Send an email to recently registered users'
  task send_email_to_recent_users: :environment do
    recent_users = User.where('updated_at <= ?', Time.zone.parse('2020/09/08 15:50:00'))
    recent_users.each do |ru|

Run in production

Execute with RAILS_ENV = production in the root directory of the project (where there is Gemfile etc.).

$ rake qiita_task:hw RAILS_ENV=production

Display task list

The tasks defined by default and the tasks you created are displayed in a row.

$ rake -T


-Creating a Rake task in Rails-Qiita

Recommended Posts

[Rails] Implement rake task
rails learning rake task, cron, whenever
[Rails] Status update using Rake task
Implement Rails pagination
[Rails] I tried to implement batch processing with Rake task
Rails: How to write a rake task nicely
[Rails] Implement search function
Implement Rails account BAN
Implement markdown in Rails
[Rails] Implement User search function
Implement follow function in Rails
Implement LTI authentication in Rails
Let's define a Rake task.
[Rails] How to implement scraping
[Rails] Implement image posting function
About regular execution of rake task of rails application on heroku
Implement simple login function in Rails
Implement a contact form in Rails
[Rails] How to implement star rating
Implement CSV download function in Rails
How to implement search functionality in Rails
How to implement ranking functionality in Rails
How to implement image posting using rails
Implement button transitions using link_to in Rails