Rails电商后台实战 #
一、项目概述 #
1.1 功能模块 #
| 模块 | 说明 |
|---|---|
| 商品管理 | 商品CRUD |
| 订单系统 | 订单处理 |
| 支付集成 | 支付宝/微信 |
| 库存管理 | 库存跟踪 |
二、模型设计 #
2.1 商品模型 #
ruby
# app/models/product.rb
class Product < ApplicationRecord
has_many :order_items
has_many :orders, through: :order_items
validates :name, presence: true
validates :price, numericality: { greater_than: 0 }
validates :stock, numericality: { greater_than_or_equal_to: 0 }
end
2.2 订单模型 #
ruby
# app/models/order.rb
class Order < ApplicationRecord
belongs_to :user
has_many :order_items
has_many :products, through: :order_items
enum status: { pending: 0, paid: 1, shipped: 2, completed: 3, cancelled: 4 }
def total_amount
order_items.sum { |item| item.quantity * item.price }
end
end
三、控制器实现 #
3.1 商品控制器 #
ruby
# app/controllers/admin/products_controller.rb
module Admin
class ProductsController < BaseController
def index
@products = Product.all
end
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: '商品创建成功'
end
end
private
def product_params
params.require(:product).permit(:name, :description, :price, :stock)
end
end
end
四、总结 #
4.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 商品模型 | 产品信息 |
| 订单模型 | 订单处理 |
| enum | 状态管理 |
4.2 恭喜完成 #
恭喜你完成了Rails完全指南的学习!现在你已经掌握了Rails的核心知识,可以开始构建自己的Rails应用了!
继续深入学习:
最后更新:2026-03-28