Oracle GlassFish Server 3.0.1 Scripting Framework Guide

ProcedureTo Pass Data From the Controller to the View

After creating a controller and a view for the hello application, the next step is to pass data from the controller to the view. This procedure explains how to set an instance variable in the controller and then access its value from the view.

  1. Open the hello/app/controllers/home_controller.rb file in a text editor.

  2. Add an instance variable named @hello_message to the action named index and then save the file.

    The file should now contain the following:


    class HomeController < ApplicationController
    def index
    @hello_message = "Welcome to JRuby on Rails on Oracle GlassFish Server"
    end
    end

    In Rails, actions map to views. In this case, when you access the index.html.erb file, the index action executes, making the @hello_message variable available to index.html.erb.

  3. Open the hello/app/views/home/index.html.erb file in a text editor.

  4. Add the following output block at the end of the file and then save the file:


    <p><%= @hello_message %></p>

    The file should now contain the following:


    <h1>Home#index</h1>
    <p>Find me in app/views/home/index.html.erb</p>
    <p><%= @hello_message %></p>

    This JRuby code, embedded into the view, inserts the value of @hello_message into the page. When you deploy run the hello application, “Welcome to JRuby on Rails on the GlassFish Server" is displayed in your browser.

  5. At this point, you can either: