123456789_123456789_123456789_123456789_123456789_

Class: ActionController::Base

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Subclasses:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Inherits: ActionController::Metal
Defined in: actionpack/lib/action_controller/base.rb

Overview

Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.

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

A sample controller could look like this:

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def create
    @post = Post.create params[:post]
    redirect_to posts_path
  end
end

Actions, by default, render a template in the app/views directory corresponding to the name of the controller and action after executing code in the action. For example, the index action of the PostsController would render the template app/views/posts/index.html.erb by default after populating the @posts instance variable.

Unlike index, the create action will not render a template. After performing its main purpose (creating a new post), it initiates a redirect instead. This redirect works by returning an external 302 Moved HTTP response that takes the user to the index action.

These two methods represent the two basic action archetypes used in Action Controllers: Get-and-show and do-and-redirect. Most actions are variations on these themes.

Requests

For every request, the router determines the value of the controller and action keys. These determine which controller and action are called. The remaining request parameters, the session (if one is available), and the full request with all the HTTP headers are made available to the action through accessor methods. Then the action is performed.

The full request object is available via the request accessor and is primarily used to query for HTTP headers:

def server_ip
  location = request.env["REMOTE_ADDR"]
  render plain: "This server hosted at #{location}"
end

Parameters

All request parameters, whether they come from a query string in the URL or form data submitted through a POST request are available through the params method which returns a hash. For example, an action that was performed through /posts?category=All&limit=5 will include { "category" => "All", "limit" => "5" } in params.

It’s also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:

<input type="text" name="post[name]" value="david">
<input type="text" name="post[address]" value="hyacintvej">

A request coming from a form holding these inputs will include { "post" => { "name" => "david", "address" => "hyacintvej" } }. If the address input had been named post[address][street], the params would have included { "post" => { "address" => { "street" => "hyacintvej" } } }. There’s no limit to the depth of the nesting.

Sessions

Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted, such as a Signup object constructed in a multi-paged process, or objects that don’t change much and are needed all the time, such as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it’s likely they could be changed unknowingly. It’s usually too much work to keep it all synchronized – something databases already excel at.

You can place objects in the session by using the session method, which accesses a hash:

session[:person] = Person.authenticate(user_name, password)

You can retrieve it again through the same hash:

"Hello #{session[:person]}"

For removing objects from the session, you can either assign a single key to nil:

# removes :person from session
session[:person] = nil

or you can remove the entire session with reset_session.

By default, sessions are stored in an encrypted browser cookie (see ::ActionDispatch::Session::CookieStore). Thus the user will not be able to read or edit the session data. However, the user can keep a copy of the cookie even after it has expired, so you should avoid storing sensitive information in cookie-based sessions.

Responses

Each action results in a response, which holds the headers and document to be sent to the user’s browser. The actual response object is generated automatically through the use of renders and redirects and requires no user intervention.

Renders

Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering of a template. Included in the Action Pack is the Action View, which enables rendering of ::ERB templates. It’s automatically configured. The controller passes objects to the view by assigning instance variables:

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

Which are then automatically available to the view:

Title: <%= @post.title %>

You don’t have to rely on the automated rendering. For example, actions that could result in the rendering of different templates will use the manual rendering methods:

def search
  @results = Search.find(params[:query])
  case @results.count
    when 0 then render action: "no_results"
    when 1 then render action: "show"
    when 2..10 then render action: "show_many"
  end
end

Read more about writing ::ERB and Builder templates in ::ActionView::Base.

Redirects

Redirects are used to move from one action to another. For example, after a create action, which stores a blog entry to the database, we might like to show the user the new entry. Because we’re following good DRY principles (Don’t Repeat Yourself), we’re going to reuse (and redirect to) a show action that we’ll assume has already been created. The code might look like this:

def create
  @entry = Entry.new(params[:entry])
  if @entry.save
    # The entry was saved correctly, redirect to show
    redirect_to action: 'show', id: @entry.id
  else
    # things didn't go so well, do something else
  end
end

In this case, after saving our new entry to the database, the user is redirected to the show method, which is then executed. Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action), and not some internal re-routing which calls both “create” and then “show” within one request.

Learn more about redirect_to and what options you have in Redirecting.

Calling multiple redirects or renders

An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:

def do_something
  redirect_to action: "elsewhere"
  render action: "overthere" # raises DoubleRenderError
end

If you need to redirect on the condition of something, then be sure to add “and return” to halt execution.

def do_something
  redirect_to(action: "elsewhere") and return if monkeys.nil?
  render action: "overthere" # won't be called if monkeys is nil
end

Constant Summary

::AbstractController::Rendering - Included

DEFAULT_PROTECTED_INSTANCE_VARIABLES

Redirecting - Included

ILLEGAL_HEADER_VALUE_REGEX

Rendering - Included

RENDER_FORMATS_IN_PRIORITY

Renderers - Included

RENDERERS

::ActiveSupport::Callbacks - Included

CALLBACK_FILTER_TYPES

RequestForgeryProtection - Included

AUTHENTICITY_TOKEN_LENGTH, CROSS_ORIGIN_JAVASCRIPT_WARNING, CSRF_TOKEN, GLOBAL_CSRF_TOKEN_IDENTIFIER, NULL_ORIGIN_MESSAGE

DataStreaming - Included

DEFAULT_SEND_FILE_DISPOSITION, DEFAULT_SEND_FILE_TYPE

ParamsWrapper - Included

EXCLUDE_PARAMETERS

Class Attribute Summary

Metal - Inherited

::AbstractController::Base - Inherited

.abstract?
.supports_path?

Returns true if the given controller is capable of rendering a path.

Class Method Summary

Metal - Inherited

.action

Returns a ::Rack endpoint for the given action name.

.controller_name

Returns the last part of the controller’s name, underscored, without the ending Controller.

.dispatch

Direct dispatch to the controller.

.make_response!,
.middleware

The middleware stack used by this controller.

.new,
.use

Pushes the given ::Rack middleware and its arguments to the bottom of the middleware stack.

.inherited, .action_encoding_template

::AbstractController::Base - Inherited

.abstract,
.abstract!

Define a controller as abstract.

.action_methods

A list of method names that should be considered actions.

.clear_action_methods!

action_methods are cached and there is sometimes a need to refresh them.

.controller_path

Returns the full controller name, underscored, without the ending Controller.

.internal_methods

A list of all internal methods for a controller.

.method_added

Refresh the cached action_methods when a new action_method is added.

.eager_load!, .inherited

::ActiveSupport::DescendantsTracker - Extended

descendants

See additional method definition at line 109.

subclasses, inherited

Instance Attribute Summary

ParamsWrapper - Included

#_wrapper_enabled?

Checks if we should perform parameters wrapping.

Instrumentation - Included

Rescue - Included

#rescue_handlers, #rescue_handlers?,
#show_detailed_exceptions?

Override this method if you want to customize when detailed exceptions must be shown.

ContentSecurityPolicy - Included

RequestForgeryProtection - Included

#_helper_methods, #_helper_methods?, #raise_on_missing_callback_actions,
#any_authenticity_token_valid?

Checks if any of the authenticity tokens from the request are valid.

#marked_for_same_origin_verification?

If the verify_authenticity_token before_action ran, verify that JavaScript responses are only served to same-origin GET requests.

#non_xhr_javascript_response?

Check for cross-origin JavaScript responses.

#protect_against_forgery?

Checks if the controller allows forgery protection.

#valid_request_origin?

Checks if the request originated from the same origin by looking at the Origin header.

#verified_request?

Returns true or false if a request is verified.

::AbstractController::Callbacks - Included

StrongParameters - Included

#params

Returns a new Parameters object that has been instantiated with the request.parameters.

#params=

Assigns the given value to the params hash.

ImplicitRender - Included

EtagWithFlash - Included

EtagWithTemplateDigest - Included

Renderers::All - Included

::ActionView::Layouts - Included

#action_has_layout=,
#action_has_layout?

Controls whether an action should be rendered using a layout.

#_conditional_layout?

::ActionView::Rendering - Included

Redirecting - Included

::AbstractController::UrlFor - Included

::ActionDispatch::Routing::UrlFor - Included

Helpers - Included

::ActionView::ViewPaths - Included

Metal - Inherited

#content_type, #headers, #location, #media_type, #middleware_stack, #middleware_stack?, #params, #params=,
#performed?

Tests if render or redirect has already happened.

#request

:attr_reader: request.

#response

:attr_reader: response.

#response=

Assign the response and mark it as committed.

#response_body=, #session, #status,
#response_code

Alias for Metal#status.

::AbstractController::Base - Inherited

#action_name

Returns the name of the action this controller is processing.

#formats

Returns the formats that can be processed by the controller.

#performed?

Tests if a response body is set.

#response_body

Returns the body of the HTTP response sent by the controller.

Instance Method Summary

ParamsWrapper - Included

#_extract_parameters, #_perform_parameter_wrapping,
#_wrap_parameters

Returns the list of parameters which will be selected for wrapped.

#_wrapper_formats

Returns the list of enabled formats.

#_wrapper_key

Returns the wrapper key which will be used to store wrapped parameters.

#process_action

Performs parameters wrapping upon the request.

Instrumentation - Included

#redirect_to, #render, #send_data, #send_file,
#append_info_to_payload

Every time after an action is processed, this method is invoked with the payload, so you can add more information.

#cleanup_view_runtime

A hook which allows you to clean up any time, wrongly taken into account in views, like database querying time.

#halted_callback_hook

A hook invoked every time a before callback is halted.

#process_action, #initialize

Rescue - Included

::ActiveSupport::Rescuable - Included

#rescue_with_handler

Delegates to the class method, but uses the instance as the subject for rescue_from handlers (method calls, instance_exec blocks).

#handler_for_rescue

Internal handler lookup.

HttpAuthentication::Token::ControllerMethods - Included

#authenticate_or_request_with_http_token

Authenticate using an HTTP Bearer token, or otherwise render an HTTP header requesting the client to send a Bearer token.

#authenticate_with_http_token

Authenticate using an HTTP Bearer token.

#request_http_token_authentication

Render an HTTP header requesting the client to send a Bearer token for authentication.

HttpAuthentication::Digest::ControllerMethods - Included

#authenticate_or_request_with_http_digest

Authenticate using an HTTP Digest, or otherwise render an HTTP header requesting the client to send a Digest.

#authenticate_with_http_digest

Authenticate using an HTTP Digest.

#request_http_digest_authentication

Render an HTTP header requesting the client to send a Digest for authentication.

HttpAuthentication::Basic::ControllerMethods - Included

DataStreaming - Included

#send_data

Sends the given binary data to the browser.

#send_file

Sends the file.

#send_file_headers!

Streaming - Included

#_process_options

Set proper cache control and transfer encoding when streaming.

#_render_template

Call render_body if we are streaming instead of usual render.

ContentSecurityPolicy - Included

RequestForgeryProtection - Included

#commit_csrf_token, #initialize, #reset_csrf_token, #compare_with_global_token, #compare_with_real_token, #csrf_token_hmac,
#form_authenticity_param

The form’s authenticity parameter.

#form_authenticity_token

Creates the authenticity token for the current request.

#global_csrf_token, #handle_unverified_request,
#mark_for_same_origin_verification!

GET requests are checked for cross-origin JavaScript after rendering.

#mask_token,
#masked_authenticity_token

Creates a masked version of the authenticity token that varies on each request.

#normalize_action_path, #per_form_csrf_token, #real_csrf_token,
#request_authenticity_tokens

Possible authenticity tokens sent in the request.

#unmask_token,
#valid_authenticity_token?

Checks the client’s masked token to see if it matches the session token.

#valid_per_form_csrf_token?,
#verify_authenticity_token

The actual before_action that is used to verify the CSRF token.

#verify_same_origin_request

If verify_authenticity_token was run (indicating that we have forgery protection enabled for this request) then also verify that we aren’t serving an unauthorized cross-origin response.

#xor_byte_strings, #decode_csrf_token, #encode_csrf_token, #generate_csrf_token, #unverified_request_warning_message

::AbstractController::Callbacks - Included

#process_action

Override AbstractController::Base#process_action to run the process_action callbacks around the normal behavior.

::ActiveSupport::Callbacks - Included

#run_callbacks

Runs the callbacks for the given event.

#halted_callback_hook

A hook invoked every time a before callback is halted.

FormBuilder - Included

#default_form_builder

Default form builder for the controller.

Flash - Included

Cookies - Included

#cookies

The cookies for the current request.

ImplicitRender - Included

BasicImplicitRender - Included

MimeResponds - Included

#respond_to

Without web-service support, an action which collects the data for displaying a list of people might look something like this:

Caching - Included

EtagWithTemplateDigest - Included

#determine_template_etag, #lookup_and_digest_template,
#pick_template_for_etag

Pick the template digest to include in the ETag.

ConditionalGet - Included

#expires_in

Sets the Cache-Control header, overwriting existing directives.

#expires_now

Sets an HTTP 1.1 Cache-Control header of no-cache.

#fresh_when

Sets the etag, last_modified, or both on the response, and renders a 304 Not Modified response if the request is already fresh.

#http_cache_forever

Cache or yield the block.

#no_store

Sets an HTTP 1.1 Cache-Control header of no-store.

#stale?

Sets the etag and/or last_modified on the response and checks them against the request.

#combine_etags

Head - Included

#head

Returns a response that has no content (merely headers).

#include_content?

Renderers - Included

#_render_to_body_with_renderer,
#render_to_body

Called by render in ::AbstractController::Rendering which sets the return value as the response_body.

Rendering - Included

#render

Renders a template and assigns the result to self.response_body.

#render_to_string

Similar to #render, but only returns the rendered template as a string, instead of setting self.response_body.

#_normalize_options

Normalize both text and status options.

#_normalize_text,
#_process_options

Process controller specific options, as status, content-type and location.

#_process_variant, #_render_in_priorities, #_set_html_content_type, #_set_rendered_content_type, #_set_vary_header, #render_to_body,
#process_action

Before processing, set the request formats in current controller formats.

::ActionView::Layouts - Included

#_default_layout

Returns the default layout for this controller.

#_include_layout?,
#_layout

This will be overwritten by _write_layout_method.

#_layout_for_option

Determine the layout for a given name, taking into account the name type.

#_normalize_layout, #_normalize_options, #initialize

::ActionView::Rendering - Included

#initialize, #render_to_body,
#view_context

An instance of a view class.

#view_context_class,
#_normalize_args

Normalize args by converting render “foo” to render action: “foo” and render “foo/bar” to render template: “foo/bar”.

#_normalize_options

Normalize options.

#_process_format

Assign the rendered format to look up context.

#_render_template

Find and render a template based on the options given.

#process

Override process to set up ::I18n proxy.

#view_renderer

Returns an object that is able to render templates.

Redirecting - Included

#redirect_back

Soft deprecated alias for #redirect_back_or_to where the fallback_location location is supplied as a keyword argument instead of the first positional argument.

#redirect_back_or_to

Redirects the browser to the page that issued the request (the referrer) if possible, otherwise redirects to the provided default fallback location.

#redirect_to

Redirects the browser to the target specified in options.

#url_from

Verifies the passed location is an internal URL that’s safe to redirect to and returns it, or nil if not.

#_allow_other_host, #_enforce_open_redirect_protection, #_ensure_url_is_http_header_safe, #_extract_redirect_to_status, #_url_host_allowed?, #_compute_redirect_to_location

::ActiveSupport::Benchmarkable - Included

#benchmark

Allows you to measure the execution time of a block in a template and records the result to the log.

UrlFor - Included

::AbstractController::UrlFor - Included

::ActionDispatch::Routing::UrlFor - Included

#initialize,
#route_for

Allows calling direct or regular named route.

#url_for

Generate a URL based on the options provided, default_url_options, and the routes defined in config/routes.rb.

#url_options

Hook overridden in controller to add request information with default_url_options.

#_routes_context, #_with_routes, #full_url_for

::ActionDispatch::Routing::PolymorphicRoutes - Included

#polymorphic_path

Returns the path component of a URL for the given record.

#polymorphic_url

Constructs a call to a named RESTful route for the given record and returns the resulting URL string.

#polymorphic_mapping, #polymorphic_path_for_action, #polymorphic_url_for_action

Helpers - Included

#helpers

Provides a proxy to access helper methods from outside the view.

::AbstractController::Helpers - Included

::AbstractController::Translation - Included

#l
#localize

Delegates to I18n.localize.

#t
#translate

Delegates to I18n.translate.

::AbstractController::Rendering - Included

#render

Normalizes arguments and options, and then delegates to render_to_body and sticks the result in self.response_body.

#render_to_body

Performs the actual template rendering.

#render_to_string

Similar to #render, but only returns the rendered template as a string, instead of setting self.response_body.

#rendered_format

Returns Content-Type of rendered content.

#view_assigns

This method should return a hash with assigns.

#_normalize_args

Normalize args by converting render "foo" to render action: "foo" and render "foo/bar" to render file: "foo/bar".

#_normalize_options

Normalize options.

#_process_options

Process extra options.

#_process_variant, #_protected_ivars,
#_normalize_render

Normalize args and options.

#_process_format

Process the rendered format.

#_set_html_content_type, #_set_rendered_content_type, #_set_vary_header

::ActionView::ViewPaths - Included

#any_templates?,
#append_view_path

Append a path to the list of view paths for the current LookupContext.

#details_for_lookup,
#lookup_context

LookupContext is the object responsible for holding all information required for looking up templates, i.e. view paths and details.

#prepend_view_path

Prepend a path to the list of view paths for the current LookupContext.

#template_exists?,
#_prefixes

The prefixes used in render “foo” shortcuts.

Metal - Inherited

#controller_name

Delegates to the class’s .controller_name.

#reset_session,
#url_for

Basic url_for that can be overridden for more robust functionality.

#dispatch, #set_request!, #set_response!, #to_a

Testing::Functional - Included

::AbstractController::Base - Inherited

#action_methods

Delegates to the class’s .action_methods.

#available_action?

Returns true if a method for the action is available and can be dispatched, false otherwise.

#controller_path

Delegates to the class’s .controller_path.

#process

Calls the action going through the entire Action Dispatch stack.

#_find_action_name

Takes an action name and returns the name of the method that will handle the action.

#_handle_action_missing

If the action name was not found, but a method called “action_missing” was found, #method_for_action will return “_handle_action_missing”.

#_valid_action_name?

Checks if the action name is valid and returns false otherwise.

#action_method?

Returns true if the name can be considered an action because it has a method defined in the controller.

#method_for_action

Takes an action name and returns the name of the method that will handle the action.

#process_action

Call the action.

#send_action

Actually call the method associated with the action.

#inspect

::ActiveSupport::Configurable - Included

#config

Reads and writes attributes from a configuration OrderedOptions.

Constructor Details

This class inherits a constructor from ActionController::Metal

Class Method Details

.without_modules(*modules)

Shortcut helper that returns all the modules included in Base except the ones passed as arguments:

class MyBaseController < ActionController::Metal
  ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
    include left
  end
end

This gives better control over what you want to exclude and makes it easier to create a bare controller class, instead of listing the modules required manually.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/base.rb', line 184

def self.without_modules(*modules)
  modules = modules.map do |m|
    m.is_a?(Symbol) ? ActionController.const_get(m) : m
  end

  MODULES - modules
end

Instance Method Details

#_protected_ivars (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/base.rb', line 252

def _protected_ivars
  PROTECTED_IVARS
end