The cleanest way to do this is with something like before_filter. This is the command at the top of your controller that gets called before any action on that controller (which you want). As a rule, you need to perform the same check for several actions in the controller, so it makes no sense to insert this check into each action directly.
Let's say you have a comment controller, and you want the editing, updating, and killing actions to be something that only a user registered in the system can do. This is very common. Let's look at an example. For brevity, I will not describe all the actions of the controller, just unique things:
class CommentsController < ApplicationController before_filter :user_logged_in?, :only => [:edit, :update, :destroy] # all your actions would go here - index, show, etc # protected def user_logged_in? redirect_to dashboard_path unless current_user end end
In the above example, the user_logged_in? will be launched before the actions for editing, updating or destruction are performed. If a render or redirection is called in this method, the rails stop and never trigger an action. Therefore, he called the filter. Instead, a render or redirect request will be executed.
The current_user method is a general helper that gives you most user authentication plugins, which is usually zero if there is no current user. Thus, our filtering method says that the rails are redirected to a specific path if the user is not logged in.
These are de facto rails to handle something like that. Very good question.
source share