7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

herokuのDBにローカルのrailsアプリケーションからアクセス

Posted at

herokuでcronみたいなのあるらしいですが、実行回数を細かく設定したり、実行時間が長いタスクの実行したいしjenkins氏で定期実行してログの保存したかったので

手元のRailsアプリケーションからherokuのDBにアクセスする方法

vi config/database.yml
config/database.yml
<%

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 %>

herokuにデプロイしたrailsアプリケーションの記述そのままです。
確認方法。

heroku run cat config/database.yml

データベースにアクセスしたいアプリケーションのENVの記述を確認します

$ heroku config
~~~~~
DATABASE_URL:               postgres://hugehuge:varvar@ec2-00-000-00-000.compute-1.amazonaws.com:5432/fogefoge
~~~~~
$ heroku run 'echo $RAILS_ENV'
~~~~~
production
~~~~~
$ heroku run 'echo $RACK_ENV'
~~~~~
production
~~~~~

ENV指定してタスクの実行なりサーバー起動すれば完了です。

DATABASE_URL=postgres://hugehuge:varvar@ec2-00-000-00-000.compute-1.amazonaws.com:5432/fogefoge RAILS_ENV=production RACK_ENV=production rails s
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?