Contents 

Ruby on Rails:
Table of Contents
Preface
Zero to Sixty: Introducing Rails
1.1. Rails Strengths
1.2. Putting Rails into Action
1.3. Organization
1.4. The Web Server
1.5. Creating a Controller
1.6. Building a View
1.7. Tying the Controller to the View
1.8. Under the Hood
1.9. What's Next?
Active Record Basics
2.1. Active Record Basics
2.2. Introducing Photo Share
2.3. Schema Migrations
2.4. Basic Active Record Classes
2.5. Attributes
2.6. Complex Classes
2.7. Behavior
2.8. Moving Forward
Active Record Relationships
3.1. belongs_to
3.2. has_many
3.3. has_one
3.4. What You Haven't Seen
3.5. Looking Ahead
Scaffolding
4.1. Using the Scaffold Method
4.2. Replacing Scaffolding
4.3. Generating Scaffolding Code
4.4. Moving Forward
Extending Views
5.1. The Big Picture
5.2. Seeing Real Photos
5.3. View Templates
5.4. Setting the Default Root
5.5. Stylesheets
5.6. Hierarchical Categories
5.7. Styling the Slideshows
Ajax
6.1. How Rails Implements Ajax
6.2. Playing a Slideshow
6.3. Using Drag-and-Drop to Reorder Slides
6.4. Drag and Drop Everything (Almost Everything)
6.5. Filtering by Category
Testing
7.1. Background
7.2. Ruby's Test::Unit
7.3. Testing in Rails
7.4. Wrapping Up
Installing Rails
1.1. Windows
2.1. OS X
3.1. Linux
Quick Reference
5.1. General
5.2. Testing
5.3. RJS (Ruby JavaScript)
5.4. Active Record
5.5. Controllers
5.6. Views
5.7. Ajax
5.8. Configuring Your Application
About the Authors
Colophon
Index
A
B
C
D
E
F
G
H
I
J
L
M
N
O
P
R
S
T
U
V
W
X
Y
Z

Ruby on Rails manual

Prev Page Next Page
Previous Page
Next Page

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.


Previous Page
Next Page