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.
$ rails g task qiita_task
namespace :qiita_task do
desc 'hello world'
task :hw do
puts 'Hello World'
end
end
$ rake qiita_task:hw
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|
ru.send_email
end
end
end
Execute with RAILS_ENV = production
in the root directory of the project (where there is Gemfile etc.).
$ rake qiita_task:hw RAILS_ENV=production
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