【问题标题】:rails database.yml not accepting ERBrails database.yml 不接受 ERB
【发布时间】:2016-06-17 15:32:01
【问题描述】:

在我的 database.yml 中,我有:

staging:
  adapter: <%= ENV['DATABASE_ADAPTER'] %>
  encoding: <%= ENV['DATABASE_ENCODING'] %>
  database: <%= ENV['DATABASE'] %>
  host: <%= ENV['DATABASE_HOST'] %>
  port: <%= ENV['DATABASE_PORT'].to_i %>
  pool: <%= ENV['DATABASE_POOL'].to_i %>
  username: <%= ENV['DATABASE_USERNAME'] %>
  password: <%= ENV['DATABASE_PASSWORD'] %>

但是,它在实际启动 puma 时不会读取 ERB 部分:

/usr/local/lib/ruby/gems/2.1.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in 
`require': Could not load 'active_record/connection_adapters/<%= ENV['DATABASE_ADAPTER'] %>_adapter'. 
Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3'
add the necessary adapter gem to the Gemfile. (LoadError)

这没有任何意义,因为在 Rails 代码中加载数据库配置:

  def database_configuration
    yaml = Pathname.new(paths["config/database"].existent.first || "")

    config = if yaml.exist?
      require "yaml"
      require "erb"
      YAML.load(ERB.new(yaml.read).result) || {}
    elsif ENV['DATABASE_URL']
      # Value from ENV['DATABASE_URL'] is set to default database connection
      # by Active Record.
      {}
    else
      raise "Could not load database configuration. No such file - #{yaml}"
    end

    config
  rescue Psych::SyntaxError => e
    raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
          "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
          "Error: #{e.message}"
  rescue => e
    raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
  end

(取自 Rails 4.2 稳定代码,我运行的是 4.2.1)

我非常困惑为什么这不起作用,有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 environment-variables yaml erb


    【解决方案1】:

    我刚刚经历了同样的事情,并看到了你的帖子。我一直在关注一个教程,该教程让我创建了一个 puma.conf 文件,其中包含以下代码:

    ActiveRecord::Base.establish_connection( YAML.load_file( "#{app_dir}/config/database.yml" )[rails_env])
    

    我修改了以下内容,一切都按预期工作:

    require 'erb'
    ActiveRecord::Base.establish_connection( YAML.load( ERB.new( File.read( "#{app_dir}/config/database.yml" )).result)[rails_env])
    

    【讨论】:

    • 我使用的是旧版本 (2.11.3),遇到了问题。升级后的 puma,没有变化。
    • 克里斯,我编辑了我的答案,不知道您是否收到了编辑通知,希望您会收到此评论的通知,新的答案将解决您的问题。
    • 如果我们不想使用 puma,例如,passenger,我们应该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多