Rails RESTful API实战 #

一、项目概述 #

1.1 API设计 #

端点 方法 说明
/api/v1/articles GET 文章列表
/api/v1/articles/:id GET 文章详情
/api/v1/articles POST 创建文章
/api/v1/articles/:id PUT 更新文章
/api/v1/articles/:id DELETE 删除文章

二、项目创建 #

2.1 创建API项目 #

bash
rails new api --api --database=postgresql
cd api

三、API实现 #

3.1 控制器 #

ruby
# app/controllers/api/v1/articles_controller.rb
module Api
  module V1
    class ArticlesController < BaseController
      def index
        @articles = Article.all
        render json: @articles
      end
      
      def show
        @article = Article.find(params[:id])
        render json: @article
      end
      
      def create
        @article = Article.new(article_params)
        
        if @article.save
          render json: @article, status: :created
        else
          render json: { errors: @article.errors }, status: :unprocessable_entity
        end
      end
      
      private
      
      def article_params
        params.require(:article).permit(:title, :body)
      end
    end
  end
end

四、总结 #

4.1 核心要点 #

要点 说明
–api API模式
render json JSON响应
状态码 status选项

4.2 下一步 #

现在你已经完成了RESTful API,接下来让我们学习 用户管理系统,深入了解Rails的用户管理实战!

最后更新:2026-03-28