获取Postgres-activerecord设置,以便在本地和Heroku中工作

时间:2015-05-06 07:03:00

标签: ruby postgresql ubuntu activerecord heroku

我正在自动创建数据库(在Sinatra应用程序中使用Rakefile)。

我希望能够从我的Linux用户“pete”(例如pete @ pete_laptop:/ path $ rake db:create)和Heroku运行rakefile。

归结为我的config / database.rb中的设置:

ActiveRecord::Base.establish_connection(
  :adapter  => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
  :host     => db.host,
  :port     => db.port,

  # pete@ubuntu_14.04_laptop--------
  # :username => 'pete',
  # :password => 'password',
  # OR
  # heroku -----------------
  # :username => db.user,
  # :password => db.password,

  :database => DB_NAME,
  :encoding => 'utf8'
)

如果我使用pete @ ubuntu_laptop设置,数据库可以在localhost中运行,但不能在Heroku中运行, 如果我使用heroku设置,则数据库在localhost中工作,但不在Heroku中工作。

如何设置此文件/我的ubuntu笔记本电脑,以便该应用程序在localhost&在Heroku?

干杯,

皮特

2 个答案:

答案 0 :(得分:1)

OK!随着帮助让它工作! 使用:

ActiveRecord::Base.establish_connection(
  :adapter  => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
  :host     => db.host,
  :port     => db.port,

  :username => ENV['PG_USER'] || db.user,
  :password => ENV['PG_PASSWORD'] || db.password,

  :database => DB_NAME,
  :encoding => 'utf8'
)

将此添加到我的shell-rc(在我的情况下为〜/ .zshrc)

export PG_USER='pete'
export PG_PASSWORD='password'

现在在我的本地环境中用户名&密码从我启动应用程序的终端中获取ENV [' PG ...]变量。

注意:' export'很重要 - 没有它,变量就不会被发送到应用程序' ENV'

答案 1 :(得分:0)

您可以使用可以像Ruby中的ENV["PG_USER"]一样访问的环境变量。如果你想在yml文件中使用它,你可以把它放在erb标签<%= ENV["PG_USER"] %>中并用erb渲染它,然后再将它传递给你的配置。

您可以在.bashrc中设置环境变量,也可以使用dotenv gem之类的东西。在heroku上,您可以设置环境变量,如heroku config:set PG_USER=postgres

但请检查heroku是否真的有必要。例如,在Rails中,heroku提供了数据库配置,因此无需对其进行配置。