---
title: "初次在Rails项目中使用PostgreSQL，纪录一些简单的步骤"
author: "tiroc"
date: "2013-11-16T10:26:01Z"
tags: ["PostgreSQL", "Rails"]
categories: ["编程语言"]
slug: "rails-postgresql"
draft: false
lastmod: "2014-02-28T14:04:53Z"
id: 1975886
url: "https://tiroc.iteye.com/blog/1975886"
---

一、安装PostgreSQL
Ubuntu 下可以用 apt-get 来安装

```bash

sudo apt-get install postgresql postgresql-contrib

```

Mac OS X 10.9.1 使用 Homebrew 安装

```bash
brew install postgresql
```


二、修改 config/database.yml
把 host: localhost 这一行的注释打开

三、创建数据库角色
1. 使用 psql 客户端连接到数据库postgres
  Mac下会默认创建当前用户的同名role：

```shell
psql postgres
```

  Ubuntu下要先使用默认创建的 postgres 用户登录：

```shell

$ sudo -u postgres psql postgres

```

2. 创建一个名为 my_app_role 的角色

```sql

postgres=# CREATE ROLE my_app_role LOGIN INHERIT;
CREATE ROLE
postgres=# ALTER USER my_app_role CREATEDB;
ALTER ROLE
postgres=# ALTER USER my_app_role WITH PASSWORD 'mypassword';
ALTER ROLE

```


四、创建数据库

```shell

$ rake db:create

```


五、如果使用 hstore
1. 以 superuser 身份登录 psql 执行以下命令：

```sql

postgres=# \c 数据库名
postgres=# CREATE EXTENSION IF NOT EXISTS "hstore";
CREATE EXTENSION

```

2. 在Gemfile中增加

```ruby

gem 'activerecord-postgres-hstore'

```


-------------------
常用命令：
\h    SQL帮助
\?     PostgreSQL帮助
\l     查看数据库列表
\dg  查看角色列表
\c    切换数据库
\dx  查看当前数据库安装的 extensions
\q    退出