Filters (before_action, skip_before_action) 2020
Filters are methods that are run before, after or around a controller action.
Filters are inherited, so if we set a filter on ApplicationController, it will be run on every controller in our application.
The before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. We can define the filter method this way:
class ApplicationController < ActionController::Base before_action :require_login private def require_login unless logged_in? flash[:error] = "You must be logged in to access this section" redirect_to new_login_url # halts request cycle end end end
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will NOT run. If there are additional filters scheduled to run after that filter, they are also cancelled.
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.
In the example above, the filter is added to ApplicationController and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it.
For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. We can prevent this filter from running before particular actions with skip_before_action:
class LoginsController < ApplicationController skip_before_action :require_login, only: [:new, :create] end
Now the LoginsController's new and create actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way.
These options can be used when adding filters too, so we can add a filter which only runs for selected actions in the first place.
For more about filter, we can have a look at Action Controller Overview.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization