新手问题 程序启动时怎么指定 development,production,test 之外的数据库?RAILS_ENV 的参数要写什么?

kitaro000 · 2015年09月15日 · 最后由 kitaro000 回复于 2015年09月16日 · 2599 次阅读

database.yml 中配置好了数据源,比如其中有个 data_99,那么我在启动服务器时怎么指定链接他? RAILS_ENV=production 会在启动程序时指定 production 数据库,这个是怎么做到的,或者说怎么自定义他?

你是偶尔想连 data_99 ?

那就新增一个 development_99 的环境,就像 development, production, test 一样,Rails 是允许你存在多个自定义环境的。

#2 楼 @huacnlee 是我 2b 了,数据源是在用到时才指定的,和程序启动时是否指定没关系,也不需要这样做

以打开 Rails console 为例,以下是 Rails 的部分源码:

#rails/railties/lib/rails/commands/console.rb
 ....
     if arguments.first && arguments.first[0] != '-'
          env = arguments.first
          #此处会判断命令行传来的环境参数是否在 available_environments 里面
          if available_environments.include? env
            options[:environment] = env
          else
            options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
          end
        end

        options
      end

      private

        #如果要自定义RAILS 环境,需要在config/environments目录下添加对应的文件,Rails 默认给你创建三个文件  production.rb, development.rb, test.rb
        def available_environments
          Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') }
        end
     .....
    #此处可以看到为什么 rails 默认的环境是development
    def environment
      options[:environment] ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
    end
....

在连接数据库的时候,rails 会去 config 目录下找 database.yml 文件,根据 RAILS_ENV 去找对应的配置

rails c -e data_99 rails s -e data_99 多个数据库,建议使用 establish_connection

#4 楼 @jasonliu 感谢你详细的解答

需要 登录 后方可回复, 如果你还没有账号请 注册新账号