Question

I created a rails app that is hosted on Heroku. Now I want to upload a ruby script that will populate my database. This script already exists and is using

PGconn.connect( :hostaddr=>"127.0.0.1", :port=>5432, :dbname=>"myDB", :user=>"MyUser", :password=>'MyPass');

This will obviously not work on Heroku.

I tried to get it using:

Rails.configuration.database_configuration

But I get

uninitialized constant Rails

How can I get the information so I can connect to my Heroku DB? Is there any way to make the same code wotk both on my localhost and on Heroku? (ps: I am using foreman and the .ENV file, if it helps)

Edit: The solution I took:

require 'yaml'
require 'erb'    
config = YAML.load(ERB.new(File.read(File.join("config","database.yml"))).result)

In config I have all the information I need to perform the DB access.

Was it helpful?

Solution

Why would you not just access ENV['DATABASE_URL'] and break it up into the constituent parts? To see how this is done, if you do heroku run bash and do cat config\database.yml you will see how Heroku does this itself.

To ensure that locally it works as well if you execute via foreman run <Scriptname> then it will be executed and the contents of your .env will be loaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top