Rails 入门项目完整指南

本文基于 Rails官方入门指南 编写,提供完整的Rails开发入门教程。

目录

  1. Rails哲学
  2. 环境准备
  3. 创建新项目
  4. 项目结构
  5. MVC基础
  6. Hello Rails
  7. 数据库模型
  8. Rails控制台
  9. Active Record基础
  10. 路由系统
  11. 控制器和动作
  12. 认证系统
  13. 缓存
  14. 富文本和文件上传
  15. 国际化
  16. 测试
  17. 代码规范
  18. 安全
  19. 部署到生产环境

Rails哲学

Rails遵循两个核心原则:

  • DRY (Don’t Repeat Yourself): 避免重复代码,提高可维护性
  • 约定优于配置 (Convention Over Configuration): 使用约定俗成的最佳实践,减少配置文件

环境准备

前置要求

  • Ruby 3.2 或更新版本
  • Rails 8.0.0 或更新版本
  • 数据库(SQLite、PostgreSQL、MySQL等)

安装Rails

gem install rails

创建新项目

基本命令

rails new store
cd store

项目选项

# 使用PostgreSQL数据库
rails new store --database=postgresql

# 跳过测试框架
rails new store --skip-test

# 使用API模式
rails new store --api

项目结构

s t o r e a b c d l l p t t v / p i o b i o u e m e p n n / b g b s p n / / f / / l t d c m v h m j a i i o o o i e a o s g c r n d e l i b s / / / t e w p l s e r l s e e / t o s r r s l s s / l / / e r s / # # # # # # # # # # # # # # # # #

MVC基础

Rails使用MVC(Model-View-Controller)架构:

  • Model: 处理数据和业务逻辑
  • View: 处理用户界面
  • Controller: 处理用户请求和响应

Hello Rails

启动服务器

rails server
# 或简写
rails s

访问 http://localhost:3000 查看应用。

生成控制器

rails generate controller Welcome index

这会创建:

  • app/controllers/welcome_controller.rb
  • app/views/welcome/index.html.erb
  • 路由配置

数据库模型

生成模型

rails generate model Product name:string description:text price:decimal

运行迁移

rails db:migrate

回滚迁移

rails db:rollback

Rails控制台

# 启动控制台
rails console
# 或简写
rails c

# 在控制台中操作数据
Product.create(name: "T-Shirt", price: 29.99)
Product.all
Product.find(1)

Active Record基础

创建记录

# 方法1:使用create
Product.create(name: "T-Shirt", price: 29.99)

# 方法2:使用new + save
product = Product.new(name: "T-Shirt", price: 29.99)
product.save

# 方法3:使用new!
Product.new!(name: "T-Shirt", price: 29.99)

查询记录

# 查找所有记录
Product.all

# 查找单个记录
Product.find(1)
Product.find_by(name: "T-Shirt")

# 条件查询
Product.where("price > ?", 20)
Product.where(price: 29.99..50.00)

# 排序
Product.order(:name)
Product.order(price: :desc)

# 限制结果
Product.limit(5)

更新记录

# 方法1:使用update
product = Product.find(1)
product.update(name: "New Name", price: 39.99)

# 方法2:使用update_all
Product.where(price: 29.99).update_all(price: 30.00)

删除记录

# 删除单个记录
product = Product.find(1)
product.destroy

# 批量删除
Product.where(price: 29.99).destroy_all

路由系统

基本路由

# config/routes.rb
Rails.application.routes.draw do
  # 根路径
  root 'welcome#index'
  
  # 资源路由
  resources :products
  
  # 自定义路由
  get '/about', to: 'pages#about'
  post '/contact', to: 'pages#contact'
end

查看路由

rails routes

控制器和动作

基本控制器

class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to @product, notice: 'Product was successfully created.'
    else
      render :new
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
      redirect_to @product, notice: 'Product was successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to products_url, notice: 'Product was successfully deleted.'
  end

  private

  def product_params
    params.require(:product).permit(:name, :description, :price)
  end
end

认证系统

使用Devise

# 添加Devise gem
gem 'devise'

# 安装Devise
rails generate devise:install
rails generate devise User
rails db:migrate

基本认证

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

缓存

页面缓存

class ProductsController < ApplicationController
  caches_page :index, :show
end

片段缓存

<% cache @product do %>
  <div class="product">
    <h2><%= @product.name %></h2>
    <p><%= @product.description %></p>
  </div>
<% end %>

富文本和文件上传

Action Text (富文本)

rails action_text:install
rails db:migrate
class Product < ApplicationRecord
  has_rich_text :description
end

Active Storage (文件上传)

rails active_storage:install
rails db:migrate
class Product < ApplicationRecord
  has_one_attached :image
end

国际化

设置语言

# config/application.rb
config.i18n.default_locale = :zh
config.i18n.available_locales = [:en, :zh]

翻译文件

# config/locales/zh.yml
zh:
  products:
    index:
      title: "产品列表"
    new:
      title: "新建产品"

测试

运行测试

# 运行所有测试
rails test

# 运行特定测试文件
rails test test/controllers/products_controller_test.rb

# 运行特定测试方法
rails test test/models/product_test.rb:test_should_be_valid

测试示例

require "test_helper"

class ProductTest < ActiveSupport::TestCase
  test "should not save product without name" do
    product = Product.new
    assert_not product.save
  end

  test "should save product with valid attributes" do
    product = Product.new(name: "Test Product", price: 29.99)
    assert product.save
  end
end

代码规范

RuboCop

# 检查代码规范
bin/rubocop

# 自动修复
bin/rubocop -a

Brakeman (安全检查)

bin/brakeman

安全

Rails内置多种安全特性:

  • SQL注入防护: 使用参数化查询
  • XSS防护: 自动转义输出
  • CSRF防护: 内置CSRF令牌
  • 会话安全: 安全的会话管理

部署到生产环境

使用Kamal部署

# 配置部署
# 编辑 config/deploy.yml

# 设置服务器
bin/kamal setup

# 部署应用
bin/kamal deploy

生产环境配置

# config/environments/production.rb
Rails.application.configure do
  # 强制使用SSL
  config.force_ssl = true
  
  # 缓存设置
  config.action_controller.perform_caching = true
  
  # 日志级别
  config.log_level = :info
end

常用命令速查

# 生成命令
rails generate model Product name:string
rails generate controller Products index show
rails generate migration AddPriceToProducts price:decimal

# 数据库命令
rails db:create
rails db:migrate
rails db:rollback
rails db:seed

# 服务器命令
rails server
rails console
rails routes

# 测试命令
rails test
rails test:prepare

下一步学习

  1. 深入Active Record: 学习关联、验证、回调
  2. 视图和布局: 掌握ERB模板和布局系统
  3. API开发: 学习构建RESTful API
  4. 性能优化: 学习缓存、数据库优化
  5. 测试驱动开发: 掌握TDD和BDD
  6. 部署和运维: 学习生产环境管理

参考资源


本文基于 Rails官方入门指南 编写,涵盖了从环境搭建到生产部署的完整流程。建议按照章节顺序学习,并在实践中加深理解。