[Rails] 레일즈 데이터베이스 설정 방법 : database.yml 작성

rails·2021년 11월 5일
0

Rails 튜토리얼

목록 보기
6/11

액티브 레코드를 사용해 데이터베이스에 연결 하려면
config/database.yml 파일을 설정 하면 된다.

처음 프로젝트를 생성 하면 아래처럼 디폴트로 생성 되어 있을 것이다.

# SQLite. Versions 3.8.0 and up are supported.
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

#으로 주석 처리된 라인은 전부 삭제 해보자.

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
  • adapter : 사용할 DBMS 종류
  • pool : 스레드 갯수
  • database : 데이터베이스명(테이블들을 담고 있는 컨테이너)
  • timeout : 쿼리 타임아웃 설정

yml 형식은 탭으로 데이터를 구분 하므로 indent에 주의 하자.

default를 상속 받아 development, test, production 세가지의 환경 설정을 꾸밀 수 있게 되어 있다.

아래 몇가지 옵션을 더 추가 할 수 있다.

  • host : 데이터베이스 호스트 주소
  • port : 데이터베이스 호스트 포트
  • encoding : 사용할 문자 코드
  • username : DBMS용 유저명
  • password : DBMS용 비밀번호
  • socket : 로컬에서 DB를 돌리는 경우 소켓 파일 주소

독자 여러분중 대다수는 github 등으로 소스코드 버전 관리를 하고 있을 것이다. 그러면 username, password 는 소스코드에 포함 되면 안된다. 따라서 linux 상의 환경변수 (ex. export RAILS_DB_USER=test@test.com) 으로 로컬 환경에 선언 하고 <%= ENV.fetch("RAILS_DB_USER") %> 같은 형식으로 불러 오는 것이 일반적이다.

환경 변수 등이 불편하고 직관적이지 않은 사람은 .yml이나 .config 같은 파일에 기록 하는 방법도 있다.

예를들면 application.yml 같은 파일을 생성 하고 아래 코드처럼 해당 파일을 로드 하는 구문을 자신의 config에 포함 시키면 된다.

    config.before_configuration do
      env_file = File.join(Rails.root, 'config', 'application.yml')
      YAML.load(File.open(env_file)).each do |key, value|
        ENV[key.to_s] = value
      end if File.exists?(env_file)
    end

꿀팁 :
yaml_db gem을 활용 하면 데이터베이스 백업/복구 를 로컬 yml 파일로 할 수 있다.

기본 Sqlite가 아니라 MySql 로 변경 하고 싶다면 mysql2 gem 파일을 추가 하고 bundle install 한 뒤에 database.yml파일을 아래처럼 수정 하면 된다.

default: &default
  adapter: mysql2
  encoding: utf8mb4
  database: testapp_development
  username: <%= ENV.fetch("RAILS_DB_USERNAME_TEST") %>
  password: <%= ENV.fetch("RAILS_DB_PASSWORD_TEST") %>
  host: 127.0.0.1
  port: 3306
  flags:
    - -COMPRESS
    - FOUND_ROWS
    - MULTI_STATEMENTS
  secure_auth: false

development:
  <<: *default
  database: testapp_development
test:
  <<: *default
  database: testapp_test

production:
  <<: *default
  database: testapp_production
  username: <%= ENV.fetch("RAILS_DB_USERNAME_REAL") %>
  password: <%= ENV.fetch("RAILS_DB_PASSWORD_REAL") %>

현업에서의 구체적인 활용 예는 다음 포스팅에서 알아 보도록 하겠다.

profile
rails

0개의 댓글