新手问题 关于 Rails 环境变量的一个头疼的问题

JiangYongKang · July 09, 2019 · Last by JiangYongKang replied at July 09, 2019 · 1934 hits

这个是 db 的配置文件

default: &default
  adapter: mysql2
  encoding: utf8
  host: localhost
  database: test_db
  username: root
  password: root
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default
  host: <%= ENV['DATABASE_HOST'] %>
  username: <%= ENV['DATABASE_USERNAME'] %>
  password: <%= ENV['DATABASE_PASSWORD'] %>

这个是我 ~/.zshrc 的配置

export DATABASE_HOST=0.0.0.0
export DATABASE_USERNAME=hahaha
export DATABASE_PASSWORD=fuckfuck

然后 RAILS_ENV=production rails c

> ActiveRecord::Base.configurations
    {
        "default"     => {
            "adapter"  => "mysql2",
            "encoding" => "utf8",
            "host"     => "localhost",
            "database" => "test_db",
            "username" => "root",
            "password" => "root",
            "pool"     => 5
        },
        "development" => {
            "adapter"  => "mysql2",
            "encoding" => "utf8",
            "host"     => "localhost",
            "database" => "test_db",
            "username" => "root",
            "password" => "root",
            "pool"     => 5
        },
        "test"        => {
            "adapter"  => "mysql2",
            "encoding" => "utf8",
            "host"     => "localhost",
            "database" => "test_db",
            "username" => "root",
            "password" => "root",
            "pool"     => 5
        },
        "production"  => {
            "adapter"  => "mysql2",
            "encoding" => "utf8",
            "host"     => nil,
            "database" => "test_db",
            "username" => nil,
            "password" => nil,
            "pool"     => 5
        }
    }

我的 .zshrc 中明明是有配置环境变量的,也执行过 source ~/.zshrc 了可是就是读不到啊。 另外 如果使用 RAILS_ENV=production DATABASE_HOST=xxxx rails c 的方式去启动是可以读到的。这个问题在 mac 和 ubuntu 上都存在。

你在 terminal 下输入env, 看看出来的是什么,有咩用 DATABASE_HOST 的配置

Reply to liuminhan

好像有点问题,我 source ~/.bashrc 之后环境变量出来了。但是 exit 之后再次 env,原本配置好的环境变量就消失了。

你用的 zsh, source ~/.zshrc

看看你默认的 sh 是哪个

Reply to liuminhan

好的,我检查一下

是不是用 credentials 好一点,省去配置各种环境变量的麻烦,如果不得不用环境变量的话,请人工忽略此回复。。。

Reply to oatw

感谢,问题已经解决了。 排查思路就是认真的检查下环境变量,从 /etc/profile 到 ~/.zshrc。需要注意的一点是要看下当前登录用户和使用的 shell。 @liuminhan 感谢

JiangYongKang closed this topic. 09 Jul 14:14
You need to Sign in before reply, if you don't have an account, please Sign up first.