跳至內容 跳至搜尋

動作控制器 API

API 控制器是 ActionController::Base 的輕量級版本,專為不需要完整 Rails 控制器所有功能的應用程式所設計,讓您可以建立僅具備 API 應用程式所需功能的控制器。

API 控制器與一般控制器不同之處在於,預設情況下它不包含瀏覽器存取通常需要的許多功能:佈局和樣板渲染、快閃訊息、資源等等。這使得整個控制器堆疊更精簡,適用於 API 應用程式。這並不意味著如果您需要這些功能就無法使用它們:它們仍然可以包含在您的應用程式中,只是它們不是預設 API 控制器堆疊的一部分。

通常,ApplicationController 是唯一繼承自 ActionController::API 的控制器。所有其他控制器則繼承自 ApplicationController

範例控制器如下所示

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

請求、回應和參數物件的工作方式與 ActionController::Base 完全相同。

渲染

預設的 API 控制器堆疊包含所有渲染器,這表示您可以在控制器中自由使用 render :json 及其同級方法。請記住,樣板不會被渲染,因此您需要確保您的控制器在所有動作中都呼叫 renderredirect_to,否則它將返回 204 No Content(無內容)。

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

重新導向

重新導向用於從一個動作移動到另一個動作。您可以在控制器中使用 redirect_to 方法,與在 ActionController::Base 中使用的方式相同。例如

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

新增行為

在某些情況下,您可能希望新增回 ActionController::Base 提供的某些 ActionController::API 預設不提供的功能,例如 MimeResponds。此模組提供 respond_to 方法。新增它非常簡單,您只需將模組包含在特定控制器中,或者如果您希望它在整個應用程式中可用,則包含在 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, # 前置回呼也應該盡可能早地執行,所以也將它們包含在底部。 AbstractController::Callbacks, # 將 rescue 附加到底部以包裝盡可能多的內容。 Rescue, # 在底部新增 instrumentation hooks,以確保它們正確地檢測所有方法。 Instrumentation, # 參數包裝器應該在 instrumentation 之前,以便它們在日誌中正確顯示 ParamsWrapper ]
 

類別公開方法

without_modules(*modules)

捷徑輔助方法,返回所有 ActionController::API 模組,但不包括作為參數傳遞的模組

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

這可以更好地控制您想要排除的內容,並且更容易建立 API 控制器類別,而不必手動列出所需的模組。

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

  MODULES - modules
end