5.5.
Controllers
5.5.1. Controller
Methods
Each public method in a controller is callable
by the default URL scheme /controller/action (/world/hello, in
this example):
class WorldController < ApplicationController
def hello
render :text => 'Hello world'
end
All request parameters, whether they come from a
GET or POST request, or from the URL, are available through the
params hash:
/world/hello/1?foo=bar
id = params[:id] # 1
foo = params[:foo] # bar
Instance variables defined in the controller's
methods are available to the corresponding view templates:
def show
@person = Person.find( params[:id])
end
Determine the type of response accepted:
def index
@posts = Post.find :all
respond_to do |type|
type.html # using defaults, which will render weblog/index.rhtml
type.xml { render :action => "index.rxml" }
type.js { render :action => "index.rjs" }
end
end
Learn more: http://api.rubyonrails.com/classes/ActionController/Base.html.
5.5.2. Render
Usually the view template with the same name as
the controller method is used to render the results.
5.5.3. Action
render :action => 'some_action' # the default. Does not need to be specified
# in a controller method called "some_action"
render :action => 'another_action', :layout => false
render :action => 'some_action', :layout => 'another_layout'
5.5.4.
Partials
Partials are stored in files whose filename
begins with an underscore (like _error, _subform,
and _listitem):
render :partial => 'subform'
render :partial => 'error', :status => 500
render :partial => 'subform', :locals => { :variable => @other_variable }
render :partial => 'listitem', :collection => @list
render :partial => 'listitem', :collection => @list, :spacer_template =>
'list_divider'
5.5.5.
Templates
Similar to rendering an action, but finds the
template based on the template root (app/views):
render :template => 'weblog/show' # renders app/views/weblog/show
5.5.6. Files
render :file => '/path/to/some/file.rhtml'
render :file => '/path/to/some/filenotfound.rhtml', status => 404, :layout => true
5.5.7. Text
render :text => "Hello World"
render :text => "This is an error", :status => 500
render :text => "Let's use a layout", :layout => true
render :text => 'Specific layout', :layout => 'special'
5.5.8. Inline
Template
Uses ERb to render the "miniature" template:
render :inline => "<%= 'hello, ' * 3 + 'again' %>"
render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" }
5.5.9. RJS
def refresh
render :update do |page|
page.replace_html 'user_list', :partial => 'user', :collection => @users
page.visual_effect :highlight, 'user_list'
end
end
5.5.10. Change
content_type
render :action => "atom.rxml", :content_type => "application/atom+xml"
5.5.11.
Redirects
redirect_to(:action => "edit")
redirect_to(:controller => "accounts", :action => "signup")
5.5.12.
Nothing
render :nothing
render :nothing, :status => 403 # forbidden
Learn more:
5.5.13. URL
Routing
In config/routes.rb:
map.connect '', :controller => 'posts', :action => 'list' # default
map.connect ':action/:controller/:id'
map.connect 'tasks/:year/:month', :controller => 'tasks',
:action => 'by_date',
:month => nil, :year => nil,
:requirements => {:year => //d{4}/,
:month => //d{1,2}/ }
Learn more: http://manuals.rubyonrails.com/read/chapter/65.
5.5.14.
Filter
Filters can change a request before or after the
controller. They can, for example, be used for authentication,
encryption, or compression:
before_filter :login_required, :except => [ :login ]
before_filter :autenticate, :only => [ :edit, :delete ]
after_filter :compress
It's also possible to use a proc for a really
small filter action:
before_filter { |controller| false if controller.params["stop_action"] }
Change the order of your filters by using
prepend_before_filter and prepend_after_filter
(like prepend_before_filter :some_filter, which will put
the some_filter at the beginning of the filter chain).
If you define a filter in a superclass, you can
skip it in the subclass:
skip_before_filter :some_filter
skip_after_filter :some_filter
Learn more:
http://api.rubyonrails.com/classes/ActionController/Filters/ClassMethods.html.
5.5.15.
Session/Flash
To save data across multiple requests, you can
use either the session or the flash hashes. A flash stores a value
(normally text) until the next request, while a session stores data
during the complete session.
session[:user] = @user
flash[:message] = "Data was saved successfully"
<%= link_to "login", :action => 'login' unless session[:user] %>
<% if flash[:message] %>
<div><%= h flash[:message] %></div>
<% end %>
5.5.15.1. Session
management
It's possible to turn off session
management:
session :off # turn session managment off
session :off, :only => :action # only for this :action
session :off, :except => :action # except for this action
session :only => :foo, # only for :foo when doing HTTPS
:session_secure => true
session :off, :only => :foo, # off for foo, if uses as Web Service
:if => Proc.new { |req| req.parameters[:ws] }
Learn more at the following site:
http://api.rubyonrails.com/classes/ActionController/SessionManagement/ClassMethods.html.
5.5.16.
Cookies
5.5.16.1.
Setting
cookies[:user_name] = "david" # => Will set a simple session cookie
cookies[:login] = { :value => "XJ-122", :expires => Time.now + 3600}
# => Will set a cookie that expires in 1 hour
5.5.16.2.
Reading
cookies[:user_name] # => "david"
cookies.size # => 2
5.5.16.3.
Deleting
cookies.delete :user_name
Option symbols for setting cookies:
value
-
The cookie's value or list of values (as an
array).
path
-
The path for which this cookie applies (defaults
to the root of the application).
domain
-
The domain for which this cookie applies.
expires
-
The time at which this cookie expires, as a
Time object.
secure
-
Whether this cookie is a secure cookie (defaults
to false). Secure cookies are transmitted only to HTTPS
servers.
Learn more: http://api.rubyonrails.com/classes/ActionController/Cookies.html. |