LoginSignup
2
6

More than 3 years have passed since last update.

【rails】production環境でバッチ処理の環境読み込みがdevelopmentになってしまうときの対処法

Last updated at Posted at 2020-04-11

実行環境

AWS EC2+RDS
Rails 5.2.4.2
Ruby 2.7

経緯

自動でメール送るバッチ処理を本番環境で行うために、
rakeファイルにタスクを書いた状態で

$ bundle exec whenever RAILS_ENV=production
(自動化の設定ファイルの実行コマンド)
を実行し、

$ bundle exec whenever --update-crontab RAILS_ENV=production
(crontabへの書き込みコマンド)
を実行しました。

その後、タスクの挙動を
$ tail -f log/cron.logで見てみると
エラーが発生していた。

エラー内容

rake aborted!
ActiveRecord::StatementInvalid: Could not find table 'テーブル名'

原因

$ bundle exec whenever RAILS_ENV=production
実行後のターミナルでの表示が以下のようになっていました。

* * * * /bin/bash -l -c 'cd /home/ec2-user/アプリ名 && RAILS_ENV=development bundle exec rake ファイル名:タスク名 --silent >> /home/ec2-user/アプリ名/log/cron.log 2>&1'

RAILS_ENV=developmentになっています。
こちらが原因です。

schedule.rbでの環境指定は以下のようにしており、問題ないはずでした。

config/schedule.rb
# cronを実行する環境変数
rails_env = ENV['RAILS_ENV'] || :development
# cronを実行する環境変数をセット
set :environment, rails_env

本番環境のコンソール上でもENV['RAILS_ENV']をいれると"production"と返ってきていました。

ですが、
以下のように、RAILS_ENVの中に何が入っているか確認すると・・・・・・
何も入ってませんでした!

$ env | grep RAILS
RAILS_ENV=

解決策

以下のコマンドを実行

$ export RAILS_ENV=production

すると

$ env | grep RAILS
RAILS_ENV=production

RAILS_ENVにproductionが入りました。

そしてもう一度$ bundle exec whenever RAILS_ENV=production
を実行すると

$ bundle exec whenever RAILS_ENV=production

* * * * * /bin/bash -l -c 'cd /home/ec2-user/relearn && RAILS_ENV=production bundle exec rake ファイル名:タスク名 --silent >> /home/ec2-user/アプリ名/log/cron.log 2>&1'

RAILS_ENV=productionに変わっています。
これで問題なく動作しました。

まとめ

・production環境で動いているように見えても、実際にgrepメソッドで確認してみるとdevelopment環境であることがある。
・デプロイしようとすると必然的に開発環境と本番環境の違いでメソッドや各機能に不具合が起きやすいので、修復には理解度の高い状態での実装が必須になる。
・Linuxコマンド少しだけでも使い慣れておいた方が良い。

参考

https://opiyotan.hatenablog.com/entry/rails-whenever
https://pikawaka.com/rails/env

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6