使用Rails框架来使用Postgresql
当使用rails new命令创建项目时,默认的数据库是sqlite,但我认为在实际工作中很少使用,所以需要将其更改为postgresql。
环境
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.2 LTS"
安装PostgreSQL
请参考以下链接进行安装:
https://www.postgresql.org/download/linux/ubuntu/
$ sudo emacs /etc/apt/sources.list.d/pgdg.list
# 下記の一文を追加
`deb http://apt.postgresql.org/pub/repos/apt/ bionic-pgdg main`
$ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install postgresql-10
创建PostgreSQL账号
$ sudo -u postgres psql
# <username>、<password> は任意の値を設定する
postgres=# create role <username> with createdb login password '<password>';
# ロールの確認
postgres=# \du
编辑PostgreSQL的连接配置
听地址 = ‘*’改为
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------
# - Connection Settings -
listen_addresses = '*' # what IP address(es) to listen on;
编辑Gemfile
gem 'pg'
将其添加到Gemfile中,并运行bundle install。
如果出现以下类似的错误并导致失败,请
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
$ sudo apt-get install libpq-dev
然后,运行bundle install。
编辑database.yml文件
default: &default
adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: <username> # とりあえずベタで
password: <password> # とりあえずベタで
host: localhost # とりあえず
timeout: 5000
development:
<<: *default
database: <project_name>_development
test:
<<: *default
database: <project_name>_test
production:
<<: *default
database: <project_name>
建立数据库
$ bundle exec rails db:create
Created database '<project_name>_development'
Created database '<project_name>_test'
实际上也确认一下数据库中的内容。
$ sudo -u postgres psql
postgres=# \l
# <project_name>_development、<project_name>_test、が作成されていることを確認