Rails数据库配置 #
一、数据库配置文件 #
1.1 配置文件位置 #
text
config/database.yml
1.2 基本配置结构 #
yaml
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: myapp_development
test:
<<: *default
database: myapp_test
production:
<<: *default
database: myapp_production
username: myapp
password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %>
二、数据库适配器 #
2.1 PostgreSQL #
yaml
default: &default
adapter: postgresql
encoding: unicode
host: localhost
port: 5432
pool: 5
username: postgres
password: <%= ENV['DB_PASSWORD'] %>
2.2 MySQL #
yaml
default: &default
adapter: mysql2
encoding: utf8mb4
host: localhost
port: 3306
pool: 5
username: root
password: <%= ENV['DB_PASSWORD'] %>
2.3 SQLite #
yaml
default: &default
adapter: sqlite3
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
<<: *default
database: storage/development.sqlite3
三、连接池配置 #
3.1 连接池参数 #
yaml
default: &default
adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
checkout_timeout: 5
reaping_frequency: 60
3.2 连接池参数说明 #
| 参数 | 说明 | 默认值 |
|---|---|---|
| pool | 连接池大小 | 5 |
| timeout | 获取连接超时时间 | 5000ms |
| checkout_timeout | 等待连接超时 | 5s |
| reaping_frequency | 清理断开连接频率 | 60s |
四、多数据库配置 #
4.1 基本多数据库 #
yaml
development:
primary:
adapter: postgresql
database: myapp_development
replica:
adapter: postgresql
database: myapp_replica
replica: true
4.2 读写分离 #
yaml
production:
primary:
adapter: postgresql
database: myapp_production
host: primary.example.com
replica:
adapter: postgresql
database: myapp_production
host: replica.example.com
replica: true
4.3 使用多数据库 #
ruby
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
connects_to database: { writing: :primary, reading: :replica }
end
# app/models/user.rb
class User < ApplicationRecord
# 自动使用主库写入,从库读取
end
# 手动切换数据库
User.connected_to(role: :reading) do
User.all
end
五、环境变量配置 #
5.1 使用环境变量 #
yaml
production:
adapter: postgresql
host: <%= ENV['DB_HOST'] %>
port: <%= ENV['DB_PORT'] || 5432 %>
database: <%= ENV['DB_NAME'] %>
username: <%= ENV['DB_USER'] %>
password: <%= ENV['DB_PASSWORD'] %>
5.2 .env文件 #
bash
# .env
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp_development
DB_USER=postgres
DB_PASSWORD=secret
六、总结 #
6.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 配置文件 | config/database.yml |
| 适配器 | PostgreSQL、MySQL、SQLite |
| 连接池 | pool、timeout配置 |
| 多数据库 | 读写分离 |
| 环境变量 | 安全存储密码 |
6.2 下一步 #
现在你已经掌握了数据库配置,接下来让我们学习 迁移基础,深入了解Rails的数据库迁移系统!
最后更新:2026-03-28