如何解决Heroku的config/database.yml文件中的错误"在此上下文中不允许映射值"

Dav*_*Sag 2 ruby heroku sinatra psych heroku-postgres

我正在向Heroku部署一个应用程序,但它很好,但是这个错误

mapping values are not allowed in this context at line 22 column 13 (Psych::SyntaxError)
Run Code Online (Sandbox Code Playgroud)

他们引用的行是heroku本身根据标准实践编写的database.yml文件的第22行.

跳转heroku run bash并查看相关文件:

<%

require 'cgi'
require 'uri'

begin
  uri = URI.parse(ENV["DATABASE_URL"])
rescue URI::InvalidURIError
  raise "Invalid DATABASE_URL"
end

raise "No RACK_ENV or RAILS_ENV found" unless ENV["RAILS_ENV"] || ENV["RACK_ENV"]

def attribute(name, value, force_string = false)
  if value
    value_string =
      if force_string
        '"' + value + '"'
      else
        value
      end
    "#{name}: #{value_string}"
  else
    ""
  end
end

adapter = uri.scheme
adapter = "postgresql" if adapter == "postgres"

database = (uri.path || "").split("/")[1]

username = uri.user
password = uri.password

host = uri.host
port = uri.port

params = CGI.parse(uri.query || "")

%>

<%= ENV["RAILS_ENV"] || ENV["RACK_ENV"] %>:
  <%= attribute "adapter",  adapter %>
  <%= attribute "database", database %>
  <%= attribute "username", username %>
  <%= attribute "password", password, true %>
  <%= attribute "host",     host %>
  <%= attribute "port",     port %>

<% params.each do |key, value| %>
  <%= key %>: <%= value.first %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

第22行是

    "#{name}: #{value_string}"
Run Code Online (Sandbox Code Playgroud)

有关如何解决此问题的任何建议?

Dav*_*Sag 12

好的,经过一些研究,我已经解决了这个问题.叹.

在我的本地计算机上,我正在加载数据库配置,如下所示:

dbconfig = YAML::load(File.open(File.join("config","database.yml")))
Run Code Online (Sandbox Code Playgroud)

但是因为ymlHeroku生成的ERB文件实际上是一个伪装的文件,我需要先解析它.

将以上行更改为:

dbconfig = YAML.load(ERB.new(File.read(File.join("config","database.yml"))).result)
Run Code Online (Sandbox Code Playgroud)

是一种享受.

  • 别忘了在你的Rakefile中要求'erb' (3认同)