本文介绍了当您不从Rails 4中的ApplicationController继承时,如何包含response_to?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails 4.1.2应用程序中有一个API控制器,该控制器不继承自Application控制器.我正在尝试包括respond_to方法并获得方法未定义的错误....因此,我需要在顶部像下面这样放置actionpack:

I have an API controller in a Rails 4.1.2 app that does not inherit from Application controller. I'm trying to include the respond_to method and get a method undefined error....So then I required actionpack at the top like below:

require 'action_pack'

class Api::V1::UsersController < Api::ApiController
  version 1

  doorkeeper_for :all
  respond_to :json

  def show
    respond_with current_user.as_json(except: :password_digest)
  end
end

我仍然得到

ActionController::RoutingError (undefined method `respond_to' for Api::V1::UsersController:Class):

但是response_to方法是MODULE ActionController :: MimeResponds :: ClassMethods的一部分,如果我打开actionpack gem的源代码,可以在子目录的action_pack文件夹下找到它.

But the respond_to method is part of the MODULE ActionController::MimeResponds::ClassMethods which can be found under the action_pack folder in a subdirectory if I open up the actionpack gem source code.

我还应该提到Api :: ApiController有一个父级RocketPants :: Base,因为我使用的是robotpant api宝石……该宝石的作者在其自述文件中指出:"RocketPants仅包含制作api的最低要求.在在不久的将来,可能会对其进行修改以与ActionController :: Base一起使用,以更好地与其他gem兼容."

I should also mention Api::ApiController has a parent RocketPants::Base since I'm using the rocketpants api gem ... The gem's author states on his README: "RocketPants only includes the bare minimum to make apis. In the near future, it may be modified to work with ActionController::Base for the purposes of better compatibility with other gems."

我对如何以独立方式(包括ActiveSupport时可以使用的方式)访问action_pack方法/库(如果可能)特别感兴趣.

I'm particularly interested in how to get access to the action_pack methods/libraries (if it's possible) in a standalone fashion, the way you can when you include activesupport.

推荐答案

还请检查您的Rails版本.在Rails 4.2及更高版本中,response_to语法已移至响应者之宝.

Also check your rails version. In Rails 4.2 and up, the respond_to syntax has been moved into theresponders gem.

宝石文件:

gem 'responders'

控制台:

bundle install
rails g responders:install

这篇关于当您不从Rails 4中的ApplicationController继承时,如何包含response_to?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:37