railsでタスクを作った。-How to build rake task-
Hi:)
最近railsで簡単なタスクを作る任務を課せられたのでメモ用にここに残す。
My boss order me to build task on rails.This is my first time so I blog here as a memo.
タスクの内容は一ヶ月より前のコメントを消すことである。
All I wanna do is to delete comments which are posted more than a month ago.
まず最初にファイルを作成する。
First of all, create a file for it.
rails g task delete_old_comments
lib/task/delete_old_comments.rake
のファイルが生成された。次に進みましょう。
Now you create a file for writing a code for task. Let’s move on.
namespace :apps do desc "delete_old_comments" task delete_old_comments: :environment do BlogComment.delete_all["created_at < ?", 1.month.ago] end end
desc
とenvironment
は必須事項である。
desc
and environment
are essential for task.
それではターミナルでbin/rake -T
を入力をして自分が作ったタスクが表示されるか確認しよう。
Now, typebin/rake -T
in terminal for checking whether your task are included on your application.
このように表示されるはずだ。
You can find like this below.
rake apps:delete_old_following_notifications # delete_old_following_notifications
続けて記述したコードが動いているか、ターミナルで入力して確認しよう。
As a test, type this to see if your codes are executing .
bin/rake apps:delete_old_comments