Home > front end >  what should I define in application controller in ruby in rails?
what should I define in application controller in ruby in rails?

Time:08-31

I don't know exactly why application_controller needs in ruby on rails

my idea is...

  1. I had watched Ruby on Rails guide, I can find out route_not_found method is in application controller, and this method can used in other controllers. so I thought application controller is different from normal controller, and this controller is for other controller.
  def route_not_found
    render file: Rails.public_path.join('404.html'), status: 404, layout: false
  end
  1. and method in application controller can be used as before_action's argument in other controller. I had defined not_login? method,
  def not_login?
    if current_user.nil?
      redirect_to login_path, notice: 'You have to log in'
    end
  end

like this, and I can used this method in other controller as before_action's argument. so I thought application_controller is for defining method which used for before_action.

is my thinking correct? I want to know what application controller's true usage

CodePudding user response:

Application controller helps abstract out shared logic of the controllers in your project. You can use it for various application wide tasks such as error handling, common methods, setting before actions, setting helper methods, etc.

As mentioned, methods that are used by multiple controllers can be placed here (ex. def current_user). However, if a method is only shared by a few controllers within a domain, it is better to place it into a different parent controller in that same domain to keep things organized. In this example, the controllers would inherit from the custom parent controller and the custom parent controller would inherit from application controller so long as the controllers inherit from application controller.

You can set before actions in application controller and call them from application controller as well, just define the method and call before_action :method_name at the top of the application controller. That before action will run before all controller actions. If you only want it to run on certain controllers, then call it the way you described, just from the controller where you want it.

  • Related