Question

If you had an OrdersController, could you define the class like this?

class OrdersController < ActionController::Base
  # stuff
end

When I generate a Rails scaffold, the only place this seems to be defined is in the ApplicationController(application_controller.rb), the other controllers created by me have something along the lines of

class OrdersController < ApplicationController
  # stuff
end

Is it correct to use the first one? In which case? I can't seem to find a good answer to this.

Was it helpful?

Solution

It is technically possible but is not advised.

Read: http://api.rubyonrails.org/classes/ActionController/Base.html

Quoted from the page:

By default, only the ApplicationController in a Rails application inherits from ActionController::Base. All other controllers in turn inherit from ApplicationController. This gives you one class to configure things such as request forgery protection and filtering of sensitive request parameters.

You may very well inherit directly from ActionController::Base as well. It is a mere case of class inheritance. Here ActionController::Base works more like an Abstract Class.

OTHER TIPS

Yes, you can certainly derive your controller class from ActionController::Base which, is the parent class of ApplicationController as you observed.

Deriving from ApplicationController is encouraged since it provides a namespace for your application. All your app controllers derive from it and all the common controller methods that you want to share in all your app controllers go in there.

So if you want to create a controller that should not inherit the methods of ApplicationController you can directly inherit from ActionController::Base for that controller.

Just in case you have not reviewed the related EdgeGuide on Controllers: http://edgeguides.rubyonrails.org/action_controller_overview.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top