跳至内容 跳至搜索

Action Controller API

API Controller 是 ActionController::Base 的一个轻量级版本,为不需要完整 Rails Controller 所提供的所有功能的应用程序而创建,它允许您创建仅包含 API 应用程序所需功能的 Controller。

与普通 Controller 不同,API Controller 默认不包含许多仅供浏览器访问所需的功能:布局和模板渲染、flash、assets 等等。这使得整个 Controller 堆栈更精简,适合 API 应用程序。但这并不意味着如果您需要这些功能就无法获得:它们都可以供您在应用程序中使用,只是它们不是默认 API Controller 堆栈的一部分。

通常,ApplicationController 是唯一继承自 ActionController::API 的 Controller。所有其他 Controller 则继承自 ApplicationController

一个示例 Controller 可能如下所示:

class PostsController < ApplicationController
  def index
    posts = Post.all
    render json: posts
  end
end

Request、response 和 parameters 对象的工作方式与 ActionController::Base 完全相同。

渲染

默认的 API Controller 堆栈包含所有渲染器,这意味着您可以在 Controller 中自由使用 render :json 及其同类方法。请记住,模板不会被渲染,因此您需要确保您的 Controller 在所有 action 中都调用了 renderredirect_to,否则它将返回 204 No Content

def show
  post = Post.find(params[:id])
  render json: post
end

重定向

重定向用于从一个 action 移动到另一个 action。您可以在 Controller 中以与 ActionController::Base 相同的方式使用 redirect_to 方法。例如:

def create
  redirect_to root_url and return if not_authorized?
  # do stuff here
end

添加新行为

在某些情况下,您可能希望添加一些 ActionController::Base 提供的、但 ActionController::API 默认不包含的功能,例如 MimeResponds。这个模块提供了 respond_to 方法。添加它很简单,只需在特定 Controller 或 ApplicationController 中包含该模块,以使其在整个应用程序中可用。

class ApplicationController < ActionController::API
  include ActionController::MimeResponds
end

class PostsController < ApplicationController
  def index
    posts = Post.all

    respond_to do |format|
      format.json { render json: posts }
      format.xml  { render xml: posts }
    end
  end
end

如果您想使用 ActionController::API 开箱即用不提供的任何其他功能,请务必检查 ActionController::Base 中包含的模块。

方法
W

常量

模块 = [ AbstractController::Rendering, UrlFor, Redirecting, ApiRendering, Renderers::All, ConditionalGet, BasicImplicitRender, StrongParameters, RateLimiting, Caching, DataStreaming, DefaultHeaders, Logging, # Before 回调也应该尽快执行,所以也把它们 # 放在底部。 AbstractController::Callbacks, # 在底部附加 rescue 以尽可能多地包裹。 Rescue, # 在底部添加 instrumentations hooks,以确保它们正确地 instrument # 所有方法。 Instrumentation, # Params wrapper 应该在 instrumentation 之前,以便在 # 日志中正确显示 ParamsWrapper ]
 

类公共方法

without_modules(*modules)

快捷助手,返回所有 ActionController::API 模块,除了作为参数传递的模块。

class MyAPIBaseController < ActionController::Metal
  ActionController::API.without_modules(:UrlFor).each do |left|
    include left
  end
end

这提供了对您想要排除的内容更好的控制,并使创建 API Controller 类变得更容易,而不是手动列出所需的模块。

# File actionpack/lib/action_controller/api.rb, line 108
def self.without_modules(*modules)
  modules = modules.map do |m|
    m.is_a?(Symbol) ? ActionController.const_get(m) : m
  end

  MODULES - modules
end