parm530
3/9/2018 - 8:12 PM

Database

What is the database.yml file?

database.yml file

  • Every Rails app will interact with a database
  • You can connect a database by setting an environment variable ENV['DATABASE_URL']
  • ALTERNATIVE: Using a configuration file in config/database.yml
development:
  adapter: postgresql
  database: blog_development
  pool: 5
  • This will connect to a database named blog_development using the postgresql adapter
  • This file contains information for 3 types of environments:
    • development: environment used on your local computer as you code and interact with the database
    • test: used when running automated test
    • production: used when your app is deployed for the world to use.
  • You can specify a URL to connect to a DB:
development:
  url: postgresql://localhost/blog_development?pool=5

  • May contain erb tags
  • Default DB is SQLite in Rails, to set up another DB upon new Rails app rails new demo_app database=mysql to use a MYSQL DB.

SQLite DB

  • SQLite is a lightweight serverless database application, best suited for development and testing
  • simple configuration for the database.yml file:
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

PSQL DB

  • In terminal, enter: sudo -u postgres creatuser rubyuser -s
    • rubyuser is the name of the user, can be any name
  • To create a password for this user:
sudo -u postgres psql
postgres=# \password rubyuser
  • To create a table for the different environments:
postgres=# CREATE DATABASE name_of_database OWNER rubyuser;

CREATE DATABASE
  • Proper name of DB should be name_development, name_test, name_production
  • ** Pressing CTRL-D will terminate postgres **

Configuring the database.yml file

  • Need to tell ruby what the password and username is for each of the database tables created
default: &default
  adapter: postgresql
  encoding: unicode
  
development:
  <<: *default
  database: name_development
  username: rubyuser
  password: <password entered in the terminal>
  
test: 
  <<: *default
  database: name_test
  username: rubyuser
  password: <..>
  
production:
  <<: *default
  database: name_production
  username: rubyuser
  password: <..>
  • For each table created above you should use a different name and a different password