Skip to content

Instantly share code, notes, and snippets.

@rocLv
Forked from stevenyap/Rails Controller.md
Created February 22, 2017 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocLv/da234d65f586209c57b8277f1d91b020 to your computer and use it in GitHub Desktop.
Save rocLv/da234d65f586209c57b8277f1d91b020 to your computer and use it in GitHub Desktop.
Rails controller cheatsheet

Flash

# supports only notice and alert by default
# the rest has to go into flash hash
redirect_to :index, notice: "success"
redirect_to :new, notice: "errors"
redirect_to :new, flash: { success: "yeah" }
flash[:info] = "updated"

flash.now[:notice] = "wrong params" # sets the flash data in the current request
flash.keep # keeps the flash data for the next request

Callbacks

before_action  :do_authentication # calls the method
after_action   :do_compresssion
around_action  :do_something      # your method needs to call yield

skip_before_action
skip_after_action
skip_around_action

before_action :do_authentication, only: [:create, :delete]
before_action :do_authentication, except: [:create, :delete]

default_url_options

  • Sets the default URL params
  • Will be overriden by params passed in
class ApplicationController < ActionController::Base
  def default_url_options
    { locale: I18n.locale }
  end
end

Set response

respond_to :json # and works with respond_with Products.all

respond_to do |format|
  format.html { render :index }
  format.json { render xml: @products.to_json }
  format.js   { render 'partials' } # for AJAX calls with button_to remote: true
  format.xml  { render xml: @products.to_xml

Filtering for authentication

class ApplicationController < ActionController::Base

  before_action :abacus_authenticate, except: :login

  def login
    # do login
  end

  def abacus_authenticate
    render text: 'Unauthorized Access', status: '401' if session[:user_id].nil?
  end
end

Types of render in controller

  • All forms of render() take optional :status, :layout, and :content_type parameters.
render(text: "Hello there!")

render(template: "<controller>/<template_name>")

render(file: path)

render(partial: name, ...)

render(nothing: true)

render(xml: stuff)

render(json: stuff, [callback: hash] )

# Output like a template
# render(inline: string, [ type: "erb"|"builder"|"coffee"|"scss" ], [ locals: hash] )
render(inline: %{
<h2>Unknown action: #{name}</h2>
Here are the request parameters:<br/> <%= debug(params) %> })

# Renders the block as an RJS template, passing in the page object.
render(:update) do |page|
  page[:cart].replace_html partial: 'cart', object: @cart
  page[:cart].visual_effect :blind_down if @cart.total_items == 1
end

Controller environment variables and methods

  • action_name
    The name of the action currently being processed.

  • cookies
    The cookies associated with the request. Setting values into this object stores cookies on the browser when the response is sent. Rails support for sessions is based on cookies. We discuss sessions in Rails Sessions, on page 339.

  • headers
    A hash of HTTP headers that will be used in the response. By default, Cache-Control is set to no-cache. You might want to set Content-Type headers for special-purpose applications. Note that you shouldn’t set cookie values in the header directly—use the cookie API to do this.

  • params
    A hash-like object containing request parameters (along with pseudopa- rameters generated during routing). It’s hash-like because you can index entries using either a symbol or a string—params[:id] and params['id'] return the same value. Idiomatic Rails applications use the symbol form.

  • request
    The incoming request object. It includes these attributes:

    • request_method returns the request method, one of :delete, :get, :head, :post, or :put.
    • method returns the same value as request_method except for :head, which it returns as :get because these two are functionally equivalent from an application point of view.
    • delete?, get?, head?, post?, and put? return true or false based on the request method.
    • xml_http_request? and xhr? return true if this request was issued by one of the Ajax helpers. Note that this parameter is independent of the method parameter.
    • url(), which returns the full URL used for the request.
    • protocol(), host(), port(), path(), and query_string(), which return components of the URL used for the request, based on the following pattern: proto- col://host:port/path?query_string.
    • domain(), which returns the last two components of the domain name of the request.
    • host_with_port(), which is a host:port string for the request.
    • port_string(), which is a :port string for the request if the port is not the default port (80 for HTTP, 443 for HTTPS).
    • ssl?(), which is true if this is an SSL request; in other words, the request was made with the HTTPS protocol.
    • remote_ip(), which returns the remote IP address as a string. The string may have more than one address in it if the client is behind a proxy.
    • env(), the environment of the request. You can use this to access values set by the browser, such as this: request.env['HTTP_ACCEPT_LANGUAGE']
    • accepts(), which is an array with Mime::Type objects that represent the MIME types in the Accept header.
    • format(), which is computed based on the value of the Accept header, with Mime::HTML as a fallback.
    • content_type(), which is the MIME type for the request. This is useful for put and post requests.
    • headers(), which is the complete set of HTTP headers.
    • body(), which is the request body as an I/O stream.
    • content_length(), which is the number of bytes purported to be in the body.

Rails leverages a gem named Rack to provide much of this functionality.
See the documentation of Rack::Request for full details.

  • response The response object, filled in during the handling of the request. Normally, this object is managed for you by Rails. As we’ll see when we look at callbacks in Callbacks, on page 346, we sometimes access the internals for specialized processing.

  • session A hash-like object representing the current session data. We describe this in Rails Sessions, on page 339.

In addition, a logger is available throughout Action Pack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment