Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 3 - Web Development: Ruby on Rails
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Web Development: Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2007-03-22

    Table of Contents:
  • Web Development: Ruby on Rails
  • 15.1 Writing a Simple Rails Application to Show System Status
  • 15.2 Passing Data from the Controller to the View
  • 15.3 Creating a Layout for Your Header and Footer

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Web Development: Ruby on Rails - 15.2 Passing Data from the Controller to the View


    (Page 3 of 4 )

    Problem

    You want to pass data between a controller and its views.

    Solution

    The view is an ERB template that is interpreted within the context of its controller object. A view cannot call any of the controller's methods, but it can access the controller's instance variables. To pass data to the view, set an instance variable of the controller.

    Here's a NovelController class, to be put into app/controllers/novel_controller.rb. You can generate stubs for it by running script/generate controller novel index.

      class NovelController < ApplicationController
       
    def index
          @title = 'Shattered View: A Novel on Rails'
          one_plus_one = 1 + 1
          increment_counter one_plus_one
        end

        def helper_method
          @help_message = "I see you've come to me for help."
        end

        private

        def increment_counter(by)
          @counter ||= 0
          @counter += by
       
    end
      end

    Since this is the Novel controller and the index action, the corresponding view is in app/views/novel/index.rhtml.

      <h1><%= @title %></h1>

      <p>I looked up, but saw only the number <%= @counter %>.</p>

      <p>"What are you doing here?" I asked sharply. "Was it <%=
      @counter.succ %> who sent you?"</p>

    The view is interpreted after NovelController#index is run. Here's what the view can and can't access:

    1. It can access the instance variables @title and @counter, because they've been defined on the NovelController object by the time NovelController#index finishes running.
    2. It can call instance methods of the instance variables @title and @counter.
    3. It cannot access the instance variable @help_message, because that variable is defined by the method helper_method, which never gets called.
    4. It cannot access the variable one_plus_one, because that's not an instance variable: it's local to the index method.
    5. Even though it runs in the context of NovelController, it cannot call any method of NovelController--neither helper_method nor set_another_variable. Nor can it call index again.

    Discussion

    The action method of a controller is responsible for creating and storing (in instance variables) all the objects the view will need to do its job. These variables might be as simple as strings, or they might be complex helper classes. Either way, most of your application's logic should be in the controller. It's okay to do things in the view like iterate over data structures, but most of the work should happen in the controller or in one of the objects it exposes through an instance variable.

    Rails instantiates a new NovelController object for every request. This means you can't persist data between requests by putting it in controller instance variables. No matter how many times you reload the page, the @counter variable will never be more than two. Every time increment_counter is called, it's called on a brand new NovelController object.

    Like any Ruby class, a Rails controller can define class variables and constants, but they will not be available to the view. Consider a NovelController that looks like this:

      class NovelController < ApplicationController
        @@numbers = [1, 2, 3]
        TITLE = 'Revenge of the Counting Numbers'
      end

    Neither @@numbers nor TITLE are accessible from within any of this controller's views. They can only be used by the controller methods.

    However, contants defined outside of the context of a controller are accessible to every view. This is useful if you want to declare the web site's name in one easy-to-change location. The config/environment.rb file is a good place to define these constants:

      # config/environment.rb
      AUTHOR = 'Lucas Carlson'
     
    ...

    It is almost always a bad idea to use global variables in object-oriented programming. But Ruby does have them, and a global variable will be available to any view once it's been defined. They will be universally available whether they were defined within the scope of the action, the controller, or outside of any scope.

      $one = 1
      class NovelController < ApplicationController
       
    $two = 2
       
    def sequel
         
    $three = 3
        end
      end

    Here's a view, sequel.rhtml, that uses those three global variables:

      Here they come, the counting numbers, <%= $one %>, <%= $two %>, <%= $three %>.

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · This article is an excerpt from the "Ruby Cookbook," published by O'Reilly. We hope...
     

    Buy this book now. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Iterating and Incrementing Strings in Ruby
    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek