How to include respond_to when you don't inherit from ApplicationController in Rails 4?

末鹿安然 提交于 2019-12-11 03:14:51

问题


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

and I still get

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

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.

EDIT:

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."

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.


回答1:


Simply make your Api::ApiController (or its parent if there is one) inherit from ActionController::Base


Good thing you mention you are using RocketPants! A quick look at their github page confirm that it is already derivated from ActionController::Base. That renders my previous answer incorrect.

So it seems you don't need to call respond_to and that instead of respond_with you should use expose, but well it's a blink guess. You should follow their documentation




回答2:


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

Gemfile:

gem 'responders'

Console:

bundle install
rails g responders:install



回答3:


I saw this error ActionController::RoutingError: undefined method 'respond_to' while I was using rails-api gem. After switching ActionController::API to ActionController::Base my error was resolved. This also fixed active_model_serializers failing to wrap render :json automatically with the corresponding serializers to my models. I may log this as an issue with the gem.




回答4:


You have to include (at least) the ActionController::RespondWith module.



来源:https://stackoverflow.com/questions/24877075/how-to-include-respond-to-when-you-dont-inherit-from-applicationcontroller-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!