Contents 

Ruby on Rails: Up and Running
Table of Contents
Copyright
Preface
Chapter 1. Zero to Sixty: Introducing Rails
Section 1.1. Rails Strengths
Section 1.2. Putting Rails into Action
Section 1.3. Organization
Section 1.4. The Web Server
Section 1.5. Creating a Controller
Section 1.6. Building a View
Section 1.7. Tying the Controller to the View
Section 1.8. Under the Hood
Section 1.9. What's Next?
Chapter 2. Active Record Basics
Section 2.1. Active Record Basics
Section 2.2. Introducing Photo Share
Section 2.3. Schema Migrations
Section 2.4. Basic Active Record Classes
Section 2.5. Attributes
Section 2.6. Complex Classes
Section 2.7. Behavior
Section 2.8. Moving Forward
Chapter 3. Active Record Relationships
Section 3.1. belongs_to
Section 3.2. has_many
Section 3.3. has_one
Section 3.4. What You Haven't Seen
Section 3.5. Looking Ahead
Chapter 4. Scaffolding
Section 4.1. Using the Scaffold Method
Section 4.2. Replacing Scaffolding
Section 4.3. Generating Scaffolding Code
Section 4.4. Moving Forward
Chapter 5. Extending Views
Section 5.1. The Big Picture
Section 5.2. Seeing Real Photos
Section 5.3. View Templates
Section 5.4. Setting the Default Root
Section 5.5. Stylesheets
Section 5.6. Hierarchical Categories
Section 5.7. Styling the Slideshows
Chapter 6. Ajax
Section 6.1. How Rails Implements Ajax
Section 6.2. Playing a Slideshow
Section 6.3. Using Drag-and-Drop to Reorder Slides
Section 6.4. Drag and Drop Everything (Almost Everything)
Section 6.5. Filtering by Category
Chapter 7. Testing
Section 7.1. Background
Section 7.2. Ruby's Test::Unit
Section 7.3. Testing in Rails
Section 7.4. Wrapping Up
Appendix A. Installing Rails
Section 1.1. Windows
Section 2.1. OS X
Section 3.1. Linux
Appendix B. Quick Reference
Section 5.1. General
Section 5.2. Testing
Section 5.3. RJS (Ruby JavaScript)
Section 5.4. Active Record
Section 5.5. Controllers
Section 5.6. Views
Section 5.7. Ajax
Section 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 for all.

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