What does before_action returning false do in Rails 4?

before_action (formerly named before_filter) is a callback that is performed before an action is executed. You can read more about controller before/after_action.

It is normally used to prepare the action or alter the execution.

The convention is that if any of the methods in the chain render or redirect, then the execution is halted and the action is not rendered.

before_action :check_permission

def hello
end

protected

def check_permission
  unless current_user.admin?
    # head is equivalent to a rendering
    head(403)
  end
end

In this example, if current_user.admin? returns false, the hello action is never performed.

The following one, instead, is an example of action setup:

before_action :find_post

def show
  # ...
end

def edit
  # ...
end

def update
  # ...
end

protected

def find_post
  @post = Post.find(params[:id])
end

In this case find_post will never return false. In fact, the purpose of this before_action is to extract a shared command from the body of the actions.

About returning false, as far as I know this is true for ActiveRecord callbacks. But for a before_action, returning false has no effect. In fact, the return value is not mentioned as important in the official documentation.

Leave a Comment

error code: 521