Help us understand the problem. What is going on with this article?

RailsのDB接続先をbranch名に従って動的に変更する

More than 1 year has passed since last update.

複数のバージョンの並行開発でDBスキーマが異なる場合、DBの接続先切り替えが非常に厄介。

そこでdatabase.yml内では式展開できることを利用し、
以下のようにするとgitブランチ名に応じて接続先を変更することが可能になる。

database.yml
default: &login
  username: root
  password: hogehoge
  adapter:  mysql
  host:     localhost
  encoding: utf8
  reconnect: true
  pool: 5

development:
  database: db_<%=
    branch = `git symbolic-ref --short HEAD`.chomp
    if branch == 'master'
      'master'
    elsif branch.start_with?('fix_')
      'fix'
    elsif branch.start_with?('pre_')
      'pre'
    else
      'development'
    end
  %>
  <<: *login

上記例
* master:db_master
* fix_で始まる:db_fix
* pre_で始まる:db_pre
* その他:db_development

TrinityT
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away