Rails API控制器 #

一、API控制器设计 #

1.1 基本结构 #

ruby
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
    end
  end
end

二、序列化 #

2.1 使用Jbuilder #

ruby
# app/views/api/v1/articles/show.json.jbuilder
json.id @article.id
json.title @article.title
json.body @article.body
json.author do
  json.id @article.author.id
  json.name @article.author.name
end

三、错误处理 #

3.1 异常处理 #

ruby
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

private

def record_not_found
  render json: { error: '资源不存在' }, status: :not_found
end

四、总结 #

4.1 核心要点 #

要点 说明
命名空间 Api::V1
序列化 Jbuilder
错误处理 rescue_from

4.2 下一步 #

现在你已经掌握了API控制器,接下来让我们学习 API认证,深入了解Rails的API认证!

最后更新:2026-03-28