Techioz Blog

Rails dotenv プロダクションの問題 [終了]

概要

[ bin/setup ] [{"RAILS_ENV"=>"test"}, "bin/rails db:reset"] succeeded
[ bin/setup ] Dropping & recreating the test database
[ bin/setup ] Executing [{"RAILS_ENV"=>"production"}, "bin/rails db:reset"]
rails aborted!
ArgumentError: Missing `secret_key_base` for 'production' environment, set this string with `bin/rails credentials:edit` (ArgumentError)

        raise ArgumentError, "Missing `secret_key_base` for '#{Rails.env}' environment, set this string with `bin/rails credentials:edit`"
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/home/mustdos/Ruby Stuff/MUPSA/config/environment.rb:5:in `<main>'
Tasks: TOP => db:reset => db:drop => db:load_config => environment
(See full trace by running task with --trace)
[ bin/setup ] [{"RAILS_ENV"=>"production"}, "bin/rails db:reset"] failed

みなさん、こんにちは。dotenv を .env.testing .env.development と .env.production で使用しようとしましたが、.env.production を実行できないようです。

この問題はどのように解決すればよいでしょうか?

解決策

Ruby on Railsのドキュメントによると

したがって、エラー メッセージが示すように、secret_key_base を設定する必要があります。

require 'securerandom'
SecureRandom.hex(64)
EDITOR="code --wait" rails credentials:edit --environment production

これにより、シークレットを含む暗号化されたファイルが復号された状態で開きます。これまで何も設定していないため、空のはずです。 次のように Secret_key_base を設定します。

secret_key_base: xxxxxxxx
other_secret: 123

これで、コード内で次のようにシークレットにアクセスできるようになります。

Rails.application.credentials.secret_key_base
Rails.application.credentials.other_secret
Rails.application.credentials.{secret_key}

PS: 開発環境では、上記の手順で何も設定しなかった場合、実際には tmp/development_secret.txt に自動的に生成される Secret_key_base が使用されます。 参考資料はこちらです。