【问题标题】:How do I include Responder in ActionController::Metal in Rails 3?如何在 Rails 3 中的 ActionController::Metal 中包含响应程序?
【发布时间】:2026-01-28 08:40:01
【问题描述】:

我正在使用一个 Rails 3 控制器,它有一个非常具体、有限的用途,我只需要它响应 response_to :json。

这个截屏视频说我的控制器可以从 ActionController::Metal 继承,然后只包含我需要让事情变得更快的功能: http://rubyonrails.org/screencasts/rails3/action-controller

当我的控制器看起来像这样时:

class FoldersController < ActionController::Metal
  respond_to :json
  def all
    respond_with Folder.all
  end
end

我得到错误:

undefined method `respond_to' for FoldersController:Class

我尝试过包括 Responder、ActionController::Responder、ActionController::Metal::Responder,但它们都不起作用。要获得此响应程序功能,我需要包含哪些内容?

【问题讨论】:

    标签: ruby ruby-on-rails-3 actioncontroller


    【解决方案1】:

    您需要包含更多类,而不仅仅是 Responder。这是我的 ApplicationController,但并非您可能需要的所有内容:

    class Api::ApplicationController < ActionController::Metal
      include ActionController::Helpers
      include ActionController::UrlFor
    
      include ActionController::Redirecting
      include ActionController::Rendering           # enables rendering
      include ActionController::ConditionalGet      # required for respond_to and respond_with
      include ActionController::MimeResponds        # enables serving different content types like :xml or :json
    
      include ActionController::Cookies             # enables cookies
      include AbstractController::Callbacks         # callbacks for your authentication logic
      include ActiveSupport::Rescuable              # enables resque_from
    
      include Rails.application.routes.url_helpers
    end
    

    【讨论】:

      【解决方案2】:

      ActionController::MimeResponds 看起来是路径。

      【讨论】:

        最近更新 更多