Rails简介 #
一、什么是Rails #
Ruby on Rails(简称Rails)是一个用Ruby语言编写的服务器端Web应用框架。它由David Heinemeier Hansson(DHH)在2004年从Basecamp项目中提取出来并开源发布。Rails遵循MVC架构模式,致力于让Web开发更加高效和愉悦。
1.1 Rails的核心组件 #
text
Rails应用架构
├── Action Pack
│ ├── Action Controller(控制器)
│ ├── Action Dispatch(路由)
│ └── Action View(视图)
├── Active Record(ORM)
│ ├── 模型层
│ ├── 数据库抽象
│ └── 关联关系
├── Active Support(工具库)
│ ├── 扩展类
│ └── 工具方法
└── Action Mailer(邮件)
├── 邮件发送
└── 邮件预览
1.2 Rails的设计哲学 #
Rails有两大核心设计原则:
| 原则 | 英文 | 说明 |
|---|---|---|
| 约定优于配置 | Convention over Configuration | 遵循约定可减少配置,提高开发效率 |
| 不要重复自己 | DRY (Don’t Repeat Yourself) | 代码应该单一、清晰、可复用 |
ruby
# 约定优于配置的体现
# 只需创建一个模型文件,Rails自动:
# - 创建对应的数据库表(复数形式)
# - 提供CRUD方法
# - 支持关联关系
class User < ApplicationRecord
# Rails自动映射到 users 表
# 自动提供 User.find, User.create 等方法
end
二、Rails发展历史 #
2.1 发展时间线 #
| 年份 | 版本 | 重要特性 |
|---|---|---|
| 2004 | 1.0 | 首次发布,MVC架构 |
| 2007 | 2.0 | RESTful支持、模板引擎改进 |
| 2010 | 3.0 | Merb合并、Asset Pipeline |
| 2013 | 4.0 | Turbolinks、Strong Parameters |
| 2016 | 5.0 | Action Cable、API模式 |
| 2019 | 6.0 | Action Text、Action Mailbox |
| 2020 | 6.1 | 关联数据变更追踪 |
| 2021 | 7.0 | Hotwire、异步查询 |
| 2022 | 7.1 | Docker支持、改进的错误页面 |
2.2 Rails的影响 #
Rails对Web开发领域产生了深远影响:
- 框架设计:影响了Django、Laravel、Phoenix等框架
- 开发理念:推广了约定优于配置的理念
- 敏捷开发:促进了敏捷开发方法的普及
- 创业文化:众多知名公司使用Rails起步(GitHub、Shopify、Airbnb等)
三、Rails的核心特点 #
3.1 MVC架构 #
text
请求流程
│
▼
┌─────────────┐
│ Router │ ─── 路由分发
└─────────────┘
│
▼
┌─────────────┐
│ Controller │ ─── 处理请求
└─────────────┘
│
├──▶ ┌─────────────┐
│ │ Model │ ─── 数据操作
│ └─────────────┘
│
▼
┌─────────────┐
│ View │ ─── 渲染页面
└─────────────┘
│
▼
响应
3.2 RESTful设计 #
Rails原生支持REST架构:
ruby
# config/routes.rb
Rails.application.routes.draw do
# 自动创建7个RESTful路由
resources :articles
end
# 生成的路由:
# GET /articles => articles#index
# GET /articles/new => articles#new
# POST /articles => articles#create
# GET /articles/:id => articles#show
# GET /articles/:id/edit => articles#edit
# PATCH /articles/:id => articles#update
# DELETE /articles/:id => articles#destroy
3.3 Active Record ORM #
ruby
# 模型定义简洁优雅
class Article < ApplicationRecord
belongs_to :user
has_many :comments
has_many :tags, through: :article_tags
validates :title, presence: true
validates :body, length: { minimum: 10 }
scope :published, -> { where(published: true) }
end
# 使用方式直观
article = Article.find(1)
article.comments.create(body: "Great article!")
Article.published.order(created_at: :desc)
3.4 约定优于配置 #
| 约定 | 说明 |
|---|---|
| 表名 | 复数形式,如 users、articles |
| 主键 | 默认为 id |
| 外键 | 表名单数_id,如 user_id |
| 时间戳 | 自动管理 created_at、updated_at |
| 文件命名 | 蛇形命名,如 user_profile.rb |
| 类命名 | 驼峰命名,如 UserProfile |
四、Rails与其他框架对比 #
4.1 与Laravel对比 #
| 特性 | Rails | Laravel |
|---|---|---|
| 语言 | Ruby | PHP |
| ORM | Active Record | Eloquent |
| 模板引擎 | ERB | Blade |
| 学习曲线 | 中等 | 平缓 |
| 社区规模 | 大 | 大 |
| 性能 | 中等 | 中等 |
| 适用项目 | 中大型 | 中大型 |
4.2 与Django对比 #
| 特性 | Rails | Django |
|---|---|---|
| 语言 | Ruby | Python |
| 设计理念 | 约定优于配置 | 显式优于隐式 |
| ORM | Active Record | Django ORM |
| Admin后台 | 需安装Gem | 内置 |
| 学习曲线 | 中等 | 平缓 |
| 适用场景 | Web应用 | Web应用 + 数据科学 |
4.3 与Express对比 #
| 特性 | Rails | Express |
|---|---|---|
| 语言 | Ruby | JavaScript |
| 类型 | 全栈框架 | 微框架 |
| 内置功能 | 丰富 | 最小 |
| 灵活性 | 中等 | 高 |
| 学习曲线 | 中等 | 平缓 |
| 适用项目 | 中大型 | 小型到大型 |
4.4 选择建议 #
选择Rails:
- 快速开发Web应用
- 喜欢约定优于配置
- 团队协作开发
- 需要完整的解决方案
- 创业项目快速原型
选择Laravel:
- 熟悉PHP生态
- 需要PHP生态集成
- 团队PHP背景
选择Django:
- 熟悉Python生态
- 需要数据科学集成
- 需要内置Admin后台
五、Rails核心概念 #
5.1 模型(Model) #
ruby
# app/models/article.rb
class Article < ApplicationRecord
# 关联
belongs_to :user
has_many :comments, dependent: :destroy
# 验证
validates :title, presence: true, length: { maximum: 100 }
validates :body, presence: true
# 作用域
scope :recent, -> { order(created_at: :desc) }
scope :published, -> { where(status: 'published') }
end
5.2 视图(View) #
erb
<!-- app/views/articles/index.html.erb -->
<h1>文章列表</h1>
<% @articles.each do |article| %>
<div class="article">
<h2><%= article.title %></h2>
<p><%= truncate(article.body, length: 100) %></p>
<%= link_to '阅读全文', article_path(article) %>
</div>
<% end %>
5.3 控制器(Controller) #
ruby
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.recent.published
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article, notice: '文章创建成功'
else
render :new, status: :unprocessable_entity
end
end
private
def article_params
params.require(:article).permit(:title, :body, :status)
end
end
5.4 路由(Routes) #
ruby
# config/routes.rb
Rails.application.routes.draw do
root 'home#index'
resources :articles do
resources :comments, only: [:create, :destroy]
member do
post :publish
end
end
namespace :admin do
resources :users
end
end
六、Rails生态系统 #
6.1 核心Gem推荐 #
| 类别 | Gem | 用途 |
|---|---|---|
| 认证 | devise | 完整的用户认证方案 |
| 授权 | pundit | 基于策略的授权 |
| 分页 | kaminari | 分页功能 |
| 搜索 | ransack | 搜索和排序 |
| 文件上传 | active_storage | 文件上传管理 |
| 后台任务 | sidekiq | 后台任务处理 |
| API | jbuilder | JSON序列化 |
| 测试 | rspec-rails | BDD测试框架 |
| 调试 | pry-rails | 增强的调试控制台 |
| 代码质量 | rubocop | 代码风格检查 |
6.2 Rails技术栈 #
text
前端层
├── Hotwire(Turbo + Stimulus)
├── Importmap
└── CSS Bundling
应用层
├── Rails框架
├── Ruby语言
└── Gem生态
数据层
├── PostgreSQL / MySQL
├── Redis(缓存/队列)
└── ElasticSearch(搜索)
部署层
├── Puma服务器
├── Nginx反向代理
└── Docker容器化
七、Rails应用场景 #
7.1 适合的项目类型 #
| 类型 | 说明 |
|---|---|
| 内容管理系统 | 博客、新闻网站 |
| 电商平台 | 在线商店、商城 |
| SaaS应用 | 在线服务、订阅系统 |
| 社交平台 | 社区、论坛 |
| API服务 | RESTful API、GraphQL |
| 企业应用 | CRM、ERP系统 |
7.2 知名Rails项目 #
| 公司/项目 | 用途 |
|---|---|
| GitHub | 代码托管平台 |
| Shopify | 电商平台 |
| Airbnb | 房屋租赁 |
| Basecamp | 项目管理 |
| SoundCloud | 音乐分享 |
| Dribbble | 设计社区 |
八、Rails 7新特性 #
8.1 Hotwire集成 #
ruby
# Turbo Drive - 无需刷新页面
<%= turbo_frame_tag "comments" do %>
<%= render @comments %>
<% end %>
# Turbo Streams - 实时更新
<%= turbo_stream.append "comments" do %>
<%= render @comment %>
<% end %>
8.2 异步查询 #
ruby
# 异步执行数据库查询
async_posts = Post.where(published: true).load_async
# 在查询完成前可以执行其他操作
do_something_else
# 需要结果时会等待查询完成
async_posts.each { |post| puts post.title }
8.3 加密属性 #
ruby
class User < ApplicationRecord
encrypts :email, deterministic: true
encrypts :credit_card_number
end
# 自动加密存储,透明解密使用
user = User.create(email: 'test@example.com')
user.email # => 'test@example.com'
九、总结 #
9.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 定义 | Ruby语言的全栈Web框架 |
| 架构 | MVC模式 |
| 设计哲学 | 约定优于配置、DRY |
| 核心组件 | Active Record、Action Pack |
| 适用场景 | Web应用、API服务 |
9.2 下一步 #
现在你已经了解了Rails的基本概念,接下来让我们学习 安装与配置,搭建你的Rails开发环境!
最后更新:2026-03-28