Action Controller Basics

Controllers and Actions

Controller Environment


cookies[:login] = { :value => "peter", :expires => 1.hour.from_now }
headers['Content-Type'] = 'application/pdf; charset=utf-8'
params
request: env, request_uri, get?, post?, xhr?, remote_ip
response
session[:user_id] = @user.id
logger.warn("Something pretty bad happened")

request.env


HTTP_ACCEPT_ENCODING = gzip,deflate
HTTP_USER_AGENT = Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3)
SERVER_PROTOCOL = HTTP/1.1
HTTP_CACHE_CONTROL = no-cache
HTTP_ACCEPT_LANGUAGE = en-us,en;q=0.5
HTTP_HOST = localhost:3000
REMOTE_ADDR = 127.0.0.1
REQUEST_PATH = /
REQUEST_URI = /
SERVER_PORT = 3000
HTTP_ACCEPT = text/xml,application/xml,application/xhtml+xml,text/html
HTTP_CONNECTION = keep-alive

Rendering a Response

Render Examples


render :text => "Hello World" 
render :action => "some_other_action", :layout => false
render :template => "weblog/show" 
render :partial => "top_menu" 
render :xml => {:name => "David"}.to_xml # Renders '<name>David</name>'
render :file => "/path/to/some/template.erb", :layout => true, :status => 404

Redirect Examples


redirect_to :back
redirect_to("/help/order_entry.html")
redirect_to :controller => 'blog', :action => 'list'
redirect_to @article #=> redirects to url_for(@article)

Cookies

Sessions

Session Configuration


# In config/initializers/session_store.rb
ActionController::Base.session = {
  :key         => '_demo_session',
  :secret      => '62af9cd9dd2ac22e3e49a3254d2a27c75c67f46d489f7526cf5531dd46e81503a78cb16750ba90b8591c626ab817404f97c3039298f9e195b3a90c701f4d0b80'
}

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store

Flash Messages


* The flash is a way to set a text message to the user in one request and then display it in the next (typically after a redirect)
* The flash is stored in the session
* flash[:notice], flash[:error]
* flash.now[:notice] = "Welcome" unless flash[:notice]
* flash.keep(:notice)

Rescuing from Exceptions


class ArticlesController < ApplicationController
  rescue_from User::NotAuthorized, :with => :deny_access  

  private
  def deny_access
    ...
  end
end

Best Practice