Rails Basics (using NetBeans 6.1)
Rails is a
web application and persistence framework that includes
everything needed to create database-backed web applications according
to
the Model-View-Control design pattern. This pattern splits the
view
(also called the presentation) into "dumb" templates that are
primarily responsible for inserting pre-built data in between HTML
tags.
The model contains the "smart" domain objects (such as Account,
Product, Person, Post) that holds all the business logic and knows how
to
persist themselves to a database. The controller handles the incoming
requests (such as Save New Account, Update Product, Show Post) by
manipulating the model and directing data to the view.
In this lab, you are going to build several simple Rails
applications step by step.
Even
though they are very simple applications, you will get an exposure to
the the whole development cycle of building a Rails application
including the creation of the
model, a controller,
and a view.
Expected duration: 100 minutes
(excluding homework)
Software Needed
Before you begin, you need to install the JDK and NetBeans IDE
software on your
computer as
described in
here.
- Java Standard Development Kit (JDK™) version
6.0 (download)
- If you already have installed JDK 5.0 or JDK 6.0, you
can skip this.
- NetBeans IDE 6.1 (download)
- When you install NetBeans IDE, it will ask you which JDK
you want to use.
- Select All, which includes Ruby module.
- MySQL (download)
- You are going to use MySQL for the database server for the
exercise.
- You can download and
install "NetBeans 6.1/GlassFish and MySQL" bundle (
download) instead of downloading and
installing them individually. This is recommended if you are
installing them for the first time,
- 5521_rails_basics.zip (download)
- It contains this document and the lab contents
- Download it and unzip in a directory of your choice
OS platforms you can use
- Windows
- Solaris x86, Solaris Sparc
- Linux
- Mac OS X
Change Log
- April 19th, 2008: Created
- May 12th, 2008: Instruction of creating database at the command
line is added
- July 31st, 2008: Homework now uses answer.html.erb instead of
display.html.erb.
- Sep. 1st, 2008: Start MySQL within NetBeans
Things to be done (by the authors of this lab)
- Add more explanation to the exercises
- Add "MySQL instruction" to the lab document
Lab Exercises
Exercise 0: Start MySQL database server
In this exercise, you are going to
start MySQL database server (of course assuming you have installed the
MySQL database server). For more detailed information on MySQ,
please refer to
MySQL 5.0
Reference Manual. For more information on how to use
MySQL with NetBeans, please see
Connecting to a
MySQL Database (using NetBeans 6.1) tutorial.
You can start the MySQL
server in a different way from the way described below. For example,
for Windows platform, it could be started as a Windows service.
(0.1) Configure MySQL
database server with NetBeans
0. Install MySQL database server (if you have not done so yet.)
1. Configure MySQL Server.
- Click Services tab.
- Right click MySQL Server at
localhost:3306[root] (not connected) and select Properties.
2. Configure Basic Properties.
- Take the default values including null Administrator password.
(Most of the sample applications
provided in this course are using these default values.)
3. Configure Admin Properties
- Click Admin Properties tab.
- Set the Path to start command
and Path to stop command as shown
below. Setting Path/URL to admin tool is optional. (The picture
below assumes you are using Windows platform.)
(0.2)
Start MySQL database server
1. Right click
MySQL Server at
localhost:3306[root] (not connected) and select
Start.

Figure-1.11: Start MySQL database server
2. Test if the MySQL database server is running.
- Right click MySQL Server at
localhost:3306[root] (not connected) and select Run Administration Tool.
- Observe that the Output window displays the uptime of the MySQL
server.
Exercise 1: Build and run
"helloworld" Rails application
In this exercise, you use the Ruby on
Rails
support in the NetBeans IDE to
create and run a simple helloworld web application. Even
though this is a very simple application, you will get an exposure to
the the whole development cycle of building a Rails application
including the creation of a
model, a controller,
and a view.

Key learning points:
- How to create a Rails project in NetBeans IDE
- Rails application directory structure
- Concept of environments - development, test, and production
- How to create a database using Rake
- How to create and populate tables using Migration
- How to create a model using Generator
- How to use Rails console
- How to create a controller using Generator
- How to add an action to the controller
- How a controller and a view are related
- How to create a related view
- How to create intense variables in an action and how they are
used in a view
- How to set up a routing
- How to trouble-shoot a problem

Tasks to be performed:
- Create a Rails project
- Create database
- Create a Model
- Create database table through migration
- Create a Controller
- Create a View
- Set URL Routing (and delete index.html)
- Build and run the application
(1.1)
Create Ruby on Rails NetBeans project
1. Create Ruby on Rails NetBeans project.
- Select File from
top-level menu of the NetBeans IDE and select New Project.
(Figure-1.11 below)

Figure-1.11: Create a new NetBeans project
- Observe that the New Project
dialog box appears.
- Choose Ruby under Categories section on the
left and Ruby on Rails
Application under Projects
section
on the right. (Figure-1.12 below)
- Click Next.

Figure-1.12: Create Ruby on Rails Application project
2. Give project a name.
- For the Project Name
field, enter helloworld.
(Figure-1.13 below) For other fields, take the default values.
- Click Finish.
Figure-1.13: Give a name to a project
3. Observe that the IDE creates various directories. Note that
the Figure-1.14
below shows the logical view of the directories.

Figure-1.14: Observe the directories that are created by the IDE (in
logical view)
4. If you want to see the actual directories that have been created,
select
Files tab window as
shown in Figure-1.15 below

Figure-1.15: Actual directories that have been created

<Study point: Directory
structure of a Rails application>
When you ask NetBeans to create a Rails project - internally
NetBeans uses the rails' helper script -, it
creates the entire directory structure for your application. Rails
knows where to find things it needs within this structure, so you don't
have to tell it explicitly.
The directory structure of a Rails application looks as
following. Please note that NetBeans uses logical names to
reflect these directories. For example, the
Controllers node represents
app/controllers directory while
Models node represents
app/models. If you click
Files view
of the project, you will see the directories mentioned below.
app
|
Holds all the code that's
specific to this particular application.
|
app/controllers
|
Holds controllers that should be
named like hello_controller.rb
for automated URL mapping.
All controllers should descend from ApplicationController
which itself
descends from ActionController::Base.
|
app/models
|
Holds models that should be
named like message.rb.
Most models will descend from ActiveRecord::Base.
|
app/views
|
Holds the template files for the
view that should be named like hello/say_hello.rhtml
for the HelloController#say_hello action.
|
app/views/layouts
|
Holds the template files for
layouts to be used with views.
This models the common header/footer method of wrapping views. In your
views, define a layout using the <tt>layout :default</tt>
and create a file named
default.rhtml. Inside default.rhtml, call <% yield %> to render
the view using this layout.
|
app/helpers
|
Holds view helpers that should
be named like hello_helper.rb. These are generated for you
automatically when using script/generate for
controllers. Helpers can be used to wrap functionality for your views
into methods.
|
config
|
Configuration files for the
Rails environment, the routing map, the database, and other
dependencies.
|
components
|
Self-contained mini-applications
that can bundle together controllers, models, and views.
|
db
|
Contains the database schema in
schema.rb.
|
db/migrate
|
Contains all the sequence of
Migrations for your schema. |
doc
|
This directory is where your
application documentation will be stored when generated using
<tt>rake doc:app</tt>
|
lib
|
Application specific libraries.
Basically, any kind of custom code that doesn't belong under
controllers, models, or helpers. This directory is in the load path.
|
public
|
The directory available for the
web server.
Contains subdirectories for images, stylesheets, and javascripts.
Also contains the dispatchers and the default HTML files.
This should be set as the DOCUMENT_ROOT of your web server.
|
script
|
Helper scripts for automation
and generation.
|
test
|
Unit and functional tests along
with fixtures. When using the script/generate scripts, template test
files will be generated for you and placed in this directory.
|
vendor
|
External libraries that the
application depends on. Also includes the plugins subdirectory.
This directory is in the load path.
|
Physical directories that are created for the Ruby on Rails project

<Study point:
Configuration/database.yml>
Rails provides the concept of environments - development, test,
production - and assumes you will be
using a different database for a different environment. Therefore each
environment has its own database connection settings.
development:
adapter: mysql
encoding: utf8
database: helloworld_development
username: root
password:
host: localhost
# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
encoding: utf8
database: helloworld_test
username: root
password:
host: localhost
production:
adapter: mysql
encoding: utf8
database: helloworld_production
username: root
password:
host: localhost
|
Configuration/database.yml
return to top of exercise
(1.2)
Create Database
1.
(If you are using NetBeans 6.1)
Create database for the project. (If you are using NetBeans 6.5,
see
below.)
- Right click helloworld project
node and select Run Rake
Task->db->create as shown Figure-1.21a below. This will
create just helloworld_development
database. (If you select Run
Rake
Task->db->create->all, databases for all three environments - helloworld_development,
hellpworld_production, helloworld_test -
are created.)

<Learning point: Rake>
Rake
is a build language for
Ruby. Rails uses Rake to automate several tasks such as creating
and dropping databases, running tests, and updating Rails support
files. For more information on Rake, please go to
http://rake.rubyforge.org.

Figure-1.21a: Create database
Trouble-shooting: If you
don't see the
create under
db, for example like in
Figure-1.23 below, it is because the newly added Rake tasks are
not refreshed yet.
Solution:
Refresh the Rake tasks as shown in Figure-1.24 below.

Figure-1.23: Rake tasks are not refreshed.

Figure-1.24: Refresh the Rake tasks
1.
(If you are using NetBeans 6.5)
Create database for the project.
- Right click helloworld project
node and select Run/Debug Rake Task
as shown in Figure-1.21b.

Figure-1.21b: RUn/Debug Rake Task (if you are using NetBeans 6.5)
- Select db:create from
the dialog box as shown in Figure-1.21c.
- Click Run.

Figure-1.21c: Run db:create (if you are using NetBeans 6.5)
Trouble-shooting: If you still don't see
db->Create option as
shown in Figure-1.21 above, you can create the database manually as
following:

Figure-1.25: Create the database manually

Figure-1.26: Create the database manually
2. Verify that the
helloworld_development
database is created using NetBeans. (This is an
optional step.)
- Click Services tab
window.
- Expand MySQL Server at
localhost:3306[root]
- Observe that the hello_development
database is present.
(Figure-1.27 below)

Figure-1.27: helloworld_development database

Figure-1.28: Make a connection to the database
- Observe that the New Database
Connection dialog box appears.
- Observe that the Database URL
field is set to jdbc:mysql://localhost:3306/helloworld_development.
- Observe that the User Name
field is set to root.
- Click OK. (Figure-1.27 below)

Figure-1.27: New Database connection
- Click OK to close the New
Database Connection dialog box.
(Figure-1.28 below)

Figure-1.28: Close the New Database Connection dialog box.
- Observe that the new database connection node, jdbc:mysql://localhost:3306/helloworld_development[..],
is added.
- Expand it.
- Click Table and observe
that there is no table created under the
database. (Figure-1.29 below)

Figure-1.29: New database connection is created
Trouble-shooting: If you don't see
MySQL
Server at localhost:3306[root] under Databases node, create a
connection manually.
- Expand Databases->Drivers.
- Right click MySQL (Connector)
driver and select Connect Using.
(Figure-1.30 below)

Figure-1.30: Connect to MySQL database
return to top of exercise
(1.3)
Create Model
In this step, you are going to use the Rails Generator to create a
model for the application. The
helloworld
application requires a
Message
model for representing messages.

<Study point: What is MVC?>
Model-view-controller (MVC) is an
architectural pattern
used in
software engineering.
In complex computer applications that present a large amount of data to
the user, a developer often wishes to separate data (model) and
user interface
(view) concerns, so that changes to the user interface will not affect
data handling, and that the data can be reorganized without changing
the user interface. The model-view-controller solves this problem by
decoupling data access and
business logic from
data presentation and user interaction,
by introducing an intermediate component: the controller.

<Study point: What is a
Model?>
In the context of MVC pattern, a Model represents domain objects such
as message, school, product, etc. A model has attributes and
methods. The attributes represents the characteristics of the
domain object, for example, a message model might have length, creator
as attributes. The methods in a model contains some business logic.
Most models have corresponding database tables. For
example, a message model will have messages table.
<Study point: What
is a Generator?>
Rails' use of runtime
reflection and metaprogramming feature of Ruby language eliminates much
of the boilerplate code
that you would otherwise have to create. You can often avoid writing
boilerplate code by using the built-in generator scripts
of Rails to create it for you. This leaves you with more time to
concentrate on
the code that really matters--your business logic.
1. Generate a Model.
- Click Projects tab
window (if it has not been selected already)
- Right click Models and
select Generate. (Figure-1.31
below)

Figure-1.31: Generate a model
- Observe that the Rails Generator
dialog box appears.
- For the Arguments field,
enter Message
greeting:string.
(Figure-1.32 below) The Message is
the name of the model and the greeting:string
is an attribute and
its type. (Figure-1.32
below)
- Read the description of Model generation.
- Click OK.

Figure-1.32: Rails generator
2. Study what files have been created.
- Observe that the Rails Generator creates a model named Message in message.rb file. (Figure-1.33
below) Note that Message is
a child class of ActiveRecord::Base
class. What this means the methods of the ActiveRecord::Base class will be inherited by the Message
class.
- Observe that the Output window lists that files that are created
as part of the model generation:
- app/models/message.rb
(Models/messages.rb in logical view). A
file that holds the methods for the Message model.
- test/unit/message_test.rb
(Unit Tests/message_test.rb in logical view).
A unit test for checking the Message model.
- test/fixtures/messages.yml
(Test Fixtures/messages.yml in logical view).
A test fixture for populating the model.
- db/migrate/001_create_messages.rb
(Database Migrations/migrate/001_create_messages.rb in logical view).
A migration file for defining the initial structure of the database.
Figure-1.33: message.rb

<Study point: What is
ActiveRecord?>
ActiveRecord is the object-relational
mapping (ORM) layer that connects business objects (models) to
database tables. It is an implementation of the Active
Record pattern described by Martin Fowler.
3. Find out what methods are
available from ActiveRecord::Base
class through Rails Console. (This is
an optional step.)
- Right click helloworld project
node and select Rails Console.
(Figure-1.34 below) This will open Rails Console in the bottom
part of the NetBeans IDE.

Figure-1.34: Open Rails Console

<Study point: What is
Rails Console?>
The Rails console gives you access to
your Rails
Environment, for
example, you can interact with the domain models of your application as
if the application is actually running. Things you can do
include performing find operations or creating a new model
object and then saving it to the database.
- Observe that Rails Console prompt is displayed in the Output
window.
- Type
ActiveRecord.methods.size.
- Observe that the number of methods of ActiveRecord class, 155, is
displayed.
- Type ActiveRecord.methods.
- Observe that the all the methods of the ActiveRecord class are
listed in the form of array. (Figure-1.35 and Figure-1.36 below)

Figure-1.35: ActiveRecord
>> ActiveRecord.methods.size
=> 155
>> ActiveRecord.methods
=> ["const_get", "as_load_path", "public_instance_methods",
"autoload?", "mattr_reader", "parent", "freeze", "const_missing",
"included_modules", "==", "mattr_writer", "attr_accessor_with_default",
"attr_internal_reader", "instance_method", "public_class_method",
"ancestors", "included_in_classes", "<", "yaml_as", "extended",
"alias_attribute", "protected_method_defined?", ">", "delegate",
"unloadable", "local_constants", "===", "include_all_modules_from",
"hash", "private_instance_methods", "attr_internal_writer",
"class_variables", "<=", "method_defined?",
"class_variable_defined?", "instance_methods", "name", "attr_internal",
"private_method_defined?", "parents", "attr_internal_accessor",
"const_set", "autoload", "include?", "protected_instance_methods",
"module_eval", "included", "mattr_accessor", "yaml_tag_class_name",
"initialize_copy", "attr_internal_naming_format=", "append_features",
"<=>", "constants", "private_class_method", "alias_method_chain",
"rails_original_const_missing", "yaml_tag_read_class", "to_s",
"public_method_defined?", "class_eval", ">=",
"attr_internal_naming_format", "const_defined?", "deprecate",
"deprecation_horizon", "deprecated_method_warning", "returning",
"subclasses_of", "`", "to_yaml_style", "require_dependency", "send!",
"require_association", "extend_with_included_modules_from",
"include_class", "to_param", "java_kind_of?", "remove_subclasses_of",
"with_options", "copy_instance_variables_from", "to_yaml_properties",
"taguri", "acts_like?", "to_yaml", "require_or_load", "blank?",
"duplicable?", "to_json", "require", "dclone", "to_yaml_node",
"handle_different_imports", "load", "extended_by", "to_query",
"instance_values", "decode64", "encode64", "decode_b", "b64encode",
"methods", "breakpoint", "enable_warnings", "silence_stream", "extend",
"object_id", "nil?", "method", "tainted?", "is_a?",
"instance_variable_get", "instance_variable_defined?",
"instance_variable_set", "silence_stderr", "gem", "display", "send",
"private_methods", "enum_for", "equal?", "com", "type", "instance_of?",
"id", "taint", "class", "instance_variables", "require_library_or_gem",
"org", "to_a", "__send__", "=~", "protected_methods", "inspect",
"__id__", "frozen?", "java", "respond_to?", "instance_eval", "untaint",
"clone", "daemonize", "to_enum", "singleton_methods", "__jtrap",
"eql?", "instance_exec", "silence_warnings", "suppress", "dup",
"kind_of?", "javax", "debugger", "public_methods"]
>>
|
Figure-1.36: ActiveRecord
methods
- Type
ActiveRecord::Base.methods.size.
- Observe that the number of methods of ActiveRecord class, 405, is
displayed.
- Type ActiveRecord::Base.methods.
- Observe that the all the methods of the ActiveRecord class are
listed in the form of array.
return to top of exercise
(1.4)
Create database table through migration

<Study point: What is a
migration?>
Migrations can manage
the evolution of a schema. It's a solution to the common problem of
adding a field to
make a new feature work in your local database, but being unsure of how
to
push that change to other developers and to the production server. With
migrations, you can describe the transformations in self-contained
classes
that can be checked into version control systems and executed against
another database that might be one, two, or five versions behind.
A simple migration example looks as following:
class AddSsl <
ActiveRecord::Migration
def self.up
add_column :accounts, :ssl_enabled,
:boolean, :default => 1
end
def self.down
remove_column :accounts, :ssl_enabled
end
end
|
The migration example above will add a column called
ssl_enabled to the
accounts table and remove
it
again, if you‘re backing out of the migration. It shows how all
migrations have two class methods
up
and
down that
describes the transformations required to implement or remove the
migration. These methods can consist of both the migration specific
methods, like
add_column and
remove_column, but may also contain
regular
Ruby code for generating data needed for the transformations. (Quoted
from
ActiveRecord:Migration
section of
api.rubonrails.org)
1. Create the database table through migration
- In the Output window of the IDE, click the link for the db/migrate/001_create_messages.rb
file. (Alternatively, you can open it by double clicking the file
under Database
Migrations->migrate->001_create_messages.rb.)
Typicall you will create a migration file yourself but Rails creates
the first migration file when a model class is generated.
- Observe that the file opens to show the self.up method, which creates a
table called messages, and the
self.down method, which
drops the messages table.
(Figure-1.41
below)

Figure-1.41: Migration
- Right-click the helloworld project
node and choose Migrate Database >
To Current Version.
(Figure-1.44 below)
This action updates the the database to include the messages table.

Figure-1.44: Migrate database to the current version
- Observe that the Output window indicates when the migration is
complete. (Figure-1.45 below)

Figure-1.45: Migration
2. Verify the
messages table
has been created. (This is an optional step.)
- Click Services tab
window.
- Right click Tables of
the helloworld_development
database and select Refresh.
(Figure-1.46 below)

Figure-1.46: Refresh the table
- Observe that the messages table
is now created with greeting column and other columns - id, created_at,
and updated_at - that are automatically created. (Figure-1.47 below)

Figure-1.47: messages table is now created
3. Display the column names of the messages table. (This is an optional
step.)
- Open the Rails console window.
- Type
Message.column_names.
- Observe that the column names of the Message class is displayed.
(Figure-1.48 below)
>> Message.column_names
=> ["id", "greeting", "created_at", "updated_at"]
>>
|
Figure-1.48: Display column
names of the Message class
return to top of exercise
(1.5)
Create a Controller
In this step, you are going to use the Rails Generator to create a
controller to interact
with the model. Also, you are going to add scaffolding code,
which
provides a simple CRUD interface for creating, reading, updating, and
deleting entries in the blog.

<Study point: What is a
Controller (or Action Controller)?>
Action Controllers are the core of a web request in Rails. They are
made up
of one or more actions that are executed on request and then either
render
a template or redirect to another
action. An action is defined as a public method on the controller,
which
will automatically be made accessible to the web-server through Rails
Routes.
A sample controller could look like the one below. There are two
actions defined -
index and
sign.
class GuestBookController
< ActionController::Base
def index
@entries = Entry.find(:all)
end
def sign
Entry.create(params[:entry])
redirect_to :action => "index"
end
end
|
Actions, by default, render
a template in
the
app/views directory
corresponding to the name of the
controller and action after executing code in the action. For example,
the
index action of the
GuestBookController
in the above example would render
the template
app/views/guestbook/index.rhtml
by default after populating
the
@entries instance
variable.
Unlike index, the sign action will not render
a template. After performing its main
purpose (creating a new entry in the guest book), it initiates a
redirect
instead. This redirect works by returning an external "302 Moved"
HTTP response that takes the user to the index action.
The index and sign actions above represent the
two basic action
archetypes used in
Action
Controllers: Get-and-show and do-and-redirect. Most actions are
variations
of these themes.
1. Generate Controller
- Click Projects tab
window. (If it has not been done already.)
- Right-click the Controllers node
and choose Generate.
(Figure-1.51 below)

Figure-1.51: Generate a controller
- Observe that the Rails Generator
dialog box appears.
- Enter Hello
in the Name field. Leave the Views
field blank.
- Read the description of the controller generator.
- Click OK. (Figure-1.52
below) This action
creates the
hello_controller.rb
file and opens the file in
the editing area.

Figure-1.52: Create a controller
- Observe that the hello_controller.rb
file is added under the Controllers node
in the Projects window. (Figure-1.53 below)

Figure-1.53: Result of creating a controller
2. Add an action to the controller.
- Add the say_hello action
to the HelloController as
shown in Code-1.54 and Figure-1.55 below. The code
fragment
that needs to be added is highlighted bold and red-colored font.
It creates Message object
instance with its greeting attribute
initialized with Hello World!
and assigns it to the @hello
instance variable.
class HelloController <
ApplicationController
def say_hello
@hello = Message.new(:greeting => "Hello World!")
end
end
|
Code-1.54 say_hello action is added

Figure-1.55: say_hello action is added

NetBeans tip: If you type
def and press tab key, it will
generate the
def ... end code
template for you.
return to top of exercise
(1.6)
Write a View

<Study point: What is a View
(or Action View)?>
View is represented by a set of templates that get displayed.
Templates share data with controllers through mutually accessible
variables. A template can be either in the form of *.rhtml
(sometimes called RHTML file) or *.erb file. (The *.erb file is
searched first by Rails.)
1. Create
say_hello.rhtml
template.
- Right click Views->hello
and select New->RHTML File.
(Figure-1.61 below)

Figure-1.61: Create new RHMTL file
- Observe that the New RHTML File
dialog box appears.
- For the File Name field,
enter say_hello.
(Figure-1.62 below)
- Click Finish.

Figure-1.62: Create say_hello.rhtml
2. Modify the IDE generated
say_hello.rhtml
file.
- Modify the IDE generated say_hello.rhtml
file as shown in
Code-1.63 and Figure-1.64 below. The code fragment that needs to
be added is highlighted in bold and red-colored font.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
My
greeting message is <%=
@hello.greeting %>
<br/>
The
current time is <%=
Time.now %>
|
Code-1.63: Modified say_hello.rhtml

Figure-1.64: Modified say_hello.rhtml
return to top of exercise
(1.7)
Set URL routing

<Study point: URL
routing>
The default Rails mapping of
URLs to controller actions is very simple and easy to understand. Rails
tries very hard to present the user with pretty URLs. Rails URLs are
simple and straightforward, not long and cryptic. Even so, you can
still customize your URLs by using the
Rails routing
facility. Rails' URL routing is flexible enough to allow you to
create virtually any URL mapping scheme. The Rails routing facility is
pure Ruby code that even allows you to
use regular expressions. Because Rails does not use the web server's
URL mapping, your custom URL mapping will work the same on every web
server.
1. Add a URL routing.
- Expand Configuration.
- Double click routes.rb to
open it in the editor window.
- Uncomment the line #28 (in the picture below - it could be
different line number in your case) and change "welcome" to "hello" as shown in Figure-1.71
below. What it means is that if the request URL is without controller
and action, the HelloController will handle it.

Figure-1.71: A new route
2. Delete index.html under Public directory.
- Right click index.html
under Public node and select Delete. (Figure-1.72 below)

Figure-1.72: Delete index.html under Public directory
- Click Yes if you get a confirmation dialog box. (Figure-1.73
below)

Figure-1.73: Confirmation dialog box
- Click Save All
icon. (Figure-1.74 below)

Figure1.74: Save all
return to top of exercise
(1.8)
Build and run the application
1. Run the application.
- Right click helloworld project
node and select Run.
(Figure-1.81 below)

Figure-1.81: Run the application
- Observe that the browser now displays with Unknown action message. (Figure-1.83
below) This is because the URL that is used to access the
application does not specify the correct path. In this
case, a default action index is
invoked. Since there is no index
action in the HelloController,
the Rails framework displays the message.

Figure-1.83: Correct path is not specified
2. Use the correct path.
- In the URL field of the browser, enter http://localhost:3005/hello/say_hello and
click Enter. The hello represents
Controller and the say_hello
represents an action.
- Observe that the correct data is now displayed in the browser.
(Figure-1.84 below)

Figure-1.84: say_hello.rhtml is displayed
3. Add
index action to the
controller.
- Modify the hello_controller.rb
as shown in Code-1.95 and
Figure-1.96 below. The code fragment that needs to be added is
highlighted in bold and red-colored font.
class HelloController <
ApplicationController
def index
say_hello # Call say_hello action method
render :action=>'say_hello' # Render a template from the
say_hello action method
end
def say_hello
@hello = Message.new(:greeting => "Hello World!")
end
end
|
Code-1.85: Add index action to the controller
- Click Save All icon. (Figure-1.86 below)

Figure-1.86: Add index action to the controller
4. Access the application without controller and action.
- Right click the project node and select Run.
- Observe that the say_hello.rhtml
template is now displayed.
(Figure-1.87 below)

Figure-1.87: say_hello.rhtml is displayed
Trouble-shooting: If you
are experiencing the problem shown in Figure-1.88 below, it is highly
likely because the MySQL database server is not running.
Solution: Start the MySQL database server as described
(0.1)
Start MySQL database server.

Figure-1.88: Error condition when the database server is not running
Trouble-shooting: If you
are experiencing the problem shown in Figure-1.89 below, it is highly
likely because the migration has not been performed after database is
created.
Solution: Perform
the migration as described
(1.4) Migrate the database.

Figure-1.89: Error condition when the database is not present
Trouble-shooting: If you
are seeing the Figure-1.90 below (instead of correct page represented
by Figure-1.84 above), it is because you have not deleted the
index.html under Public node as described
above.
Solution: Delete index.html under Public node.

Figure-1.90: index.html in Public node is displayed
Trouble-shooting: If you
are seeing the Figure-1.91 below (instead of correct page represented
by Figure-1.84 above), it is because did not set the correct routing in
the Configuration/routes.rb as described
above.
Solution: Set the correct routing.

Figure-1.91: Routing error
Trouble-shooting: If you see the error condition as shown in
Figure-1.92 below, one possible explanation might be because the
say_hello did not have quote as
shown in Code-1.93 below. Solution is to have quote as shown in
Code-1.94 below.

Figure-1.92: Error condition
class HelloController <
ApplicationController
def index
say_hello
render :action=>say_hello #
Incorrect syntax
end
def say_hello
@hello=Message.new(:greeting=>"Hello World!")
end
end
|
Figure-1.93: Incorrect usage of render method
class HelloController <
ApplicationController
def index
say_hello
render :action=>'say_hello' #
Correct syntax
end
def say_hello
@hello=Message.new(:greeting=>"Hello World!")
end
end |
Figure-1.94: Correct usage of render method
return to top of exercise
Solution
The solution of this exercise is provided as a ready-to-build NetBeans
project -
<LAB_UNZIP_DIR>/rails_basics/solutions/exercise1/helloworld.
You should be able to build and run the project. (You might
still have
to create the database as described in
step 1.2
above and the migrate the database described
in
step 1.4 above before you run the application.)
Summary
In this exercise, you have learned how
to build a simple
Rails application going through the development steps of creating
model.
controller, and view. You also learned how to migrate a database.
return
to the top
Exercise 2: Add another field to a Model
(2.1)
Add another field to a table through migration
1. Generate a new migration.
- Right click helloworld project
node and select Generate.
(Figure-2.11 below)

Figure-2.11: Perform Generation
- Observe that the Rails Generator
dialog box appears.
- Select migration
from the Generate
drop-down menu.
- For the Arguments field, enter AddNameToMessage name:string.
(Figure-2.12 below)
- Click OK. This will create a new migration file.

Figure-2.12: Generate a migration
- Observe that the IDE displays 002_add_name_to_message.rb
in the editor window. (Figure-2.13 below) At this point, a new
migration file is created but not yet used to create a new column to
the messages table.

Figure-2.13: Generation is done
2. Migrate database.
- Right click project node and select Migrate Database->To Current Version.
(Figure-2.14 below)

Figure-2.14: Migrate the database to the current version
- Observe that the Output window of the IDE displays the result of
migration. (Figure-2.15 below) At this point, the messages table has a new column
called name.

Figure-2.15: Migration is done
3. Verify that the new column
name is
now added to the
messages table.
(This is an optional step.)
- Select Services tab
window.
- Expand jdbc:mysql://localhost:3306/helloworld_development[root..]
- Expand Tables.
- Expand messages.
- Observe that the name column
is present. (Figure-2.16 below)

Figure-2.16: Verify that the name column is present
return to top of exercise
(2.2)
Modify the controller
In this step, you are going to make a change in the
say_hello action so that it assigns
a value to the
name attribute
of the
@hello .
1. Modify the HelloController.
- Add a new line as shown in Code-2.21 and Figure-2.22 below. The
code fragment that needs to be modified is highlighted in bold and
red-colored font.
class HelloController <
ApplicationController
def index
say_hello
render :action=>'say_hello'
end
def say_hello
@hello = Message.new(:greeting => "Hello World!")
@hello.name = "Sang
Shin"
end
end
|
Code-2.21: Modified controller

Figure-2.22: Modified controller
return to top of exercise
(2.3)
Modify the view
In this step, you are going to modify the
say_hello.rhtml to display
the
name attribute of the
@hello instance variable.
1. Modify the
say_hello.rhtml
as shown in Code-2.31 and Figure-2.32
below. The code fragment that needs to be added is highlighted in bold
and red-colored font.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
My greeting message is <%= @hello.greeting %>
<br/>
The current time is <%= Time.now %>
<br/>
My name
is <%= @hello.name %>
|
Code-2.31: Modified say_hello.rhtml

Figure-2.32: Modified say_helllo.rhtml
return to top of exercise
(2.4)
Save the changes and Refresh the browser
1. Save the changes.
- Click Save All icon. (Figure-2.41 below)

Figure-2.41: Save the changes
2. Refresh the browser to see the result.
- Click Refresh icon of the browser.
- Observe that the name field of the @hello is now displayed.
(Figure-2.42 below)

Note that you did not have to
recompile, redeploy the application to see the change. Instead,
you save the change and then refresh the browser.

Figure-2.42: Result is displayed
return to top of exercise
(2.5)
Display log file
The log files could be used for debugging purpose.
1. Display the
development.log
file.
- Expand Logs.
- Double click development.log.
- Observe that the contents of the file is displayed in the editor
window.
- Observe the contents of the Parameters hash - controller is set hello and action is set say_hello. (Figure-2.51 below)
(2.6)
Modify the view
In this step, you are going to modify
say_hello.rhtml
so that the contents can be printed multiple times. (Yes, it is a
bit of meaningless exercise but the goal is to show how natural the
code
looks leveraging the power of Ruby language.)
1. Modify the
say_hello.rhtml
as shown in Code-2.61 and Figure-2.62 below. The
code fragment that needs to be modified is highlighted in bold and
red-colored font.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
<%
4.times do |count| %>
Counter <%= count %>
<br/>
My greeting message is <%= @hello.greeting %>
<br/>
The current time is <%= Time.now %>
<br/>
My name is <%= @hello.name %>
<br/>
<% end
%>
|
Code-2.61: Modified view
Figure-2.62: Modified view
2. Refresh the browser.
- Click refresh icon of the browser.
- Observe the result. (Figure-2.63)

Figure-2.63: Result of display modified view
return to top of exercise
Solution
The solution of this exercise is provided as a ready-to-build NetBeans
project - <LAB_UNZIP_DIR>/rails_basics/solutions/exercise2/helloworld.
You should be able to build and run the project.
Summary
In this exercise, you have learned how
to add a new field to a Model through database migration.
return
to the top
Exercise 3: Add another template to the
application
(3.1)
Create a new template
1. Create
say_goodbye.html.erb
file.
- Right click Views->hello
and select New->ERB File.
(Figure-3.11 below)

Figure-3.11: Create a new *.html.erb file
- For File Name field,
enter say_goodbye.html.
(Figure-3.12 below)
- Click Finish.

Figure-3.12: Give a name to the new template
2. Modify the IDE generated
say_goodbye.html.erb
file.
- Modify the IDE generated say_goodbye.html.erb
file as shown in
Code-3.13 and Figure-3.14 below. The code fragment that needs to
be added is highlighted in bold and red-colored font.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
<%=
@goodbye.greeting %>
<%=
link_to "Go to Hello", :action=>"say_hello" %>
|
Code-3.13: Modified say_goodbye.html.erb

Figure-3.14: Modified say_goodbye.html.erb
return to top of exercise
(3.2)
Modify existing template
1. Modify
say_hello.rhtml as
shown in Code-3.21 and Figure-3.22 below. The code fragment that
needs to be added is highlighted in bold and red-colored font.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
<% 4.times do |count| %>
Counter <%= count %>
<br/>
My greeting message is <%= @hello.greeting %>
<br/>
The current time is <%= Time.now %>
<br/>
My name is <%= @hello.name %>
<br/>
<% end %>
<%=
link_to "Go to Goodbye", :action=>"say_goodbye" %>
|
Code-3.21: Modified say_hello.rhtml

Figure-3.22: Modified say_hello.rhtml

NetBeans tip: NetBeans comes with
extensive ready-to-use code templates for Ruby and Rails
programming. For adding
<%=
link_to .. %>, just type
lia and press tab key. For
adding
<%= .. %>, type
re and press tab key. Of
course, you can create your own. For the listing of these code
templates, select
Tools->Options
and then select
Editor and
Code Templates and then select
Language option from the drop-down menu. (Figure-3.23 below)

Figure-3.23: Code templates
return to top of exercise
(3.3)
Add a new action
1. Modify
hello_controller.rb
as shown in Code-3.31 and Figure-3.32 below. The code fragment
that needs to be added is highlighted in bold and red-colored font.
class HelloController <
ApplicationController
def index
say_hello
render :action=>'say_hello'
end
def say_hello
@hello = Message.new(:greeting => "Hello World!")
@hello.name = "Sang Shin"
end
def say_goodbye
@goodbye = Message.new(:greeting=>"Goodbye")
end
end
|
Code-3.31: Modified hello_controller.rb

Figure-3.32: Modified hello_controller.rb
return to top of exercise
(3.4)
Save all the changes and refresh the browser
1. Click Save All icon. (Figure-3.41 below)

Figure-3.41: Save all changes
2. Refresh the browser.
- Click Refresh icon of the browser.
- Click Go to Goodbye link.

Figure-3.42: Click Go to Goodbye link.
3. Go to Hello template.
- Click Go to Hello link. (Figure-3.43 below)

Figure-3.43: Go to Hello
return to top of exercise
Solution
The solution of this exercise is provided as a ready-to-build NetBeans
project -
<LAB_UNZIP_DIR>/rails_basics/solutions/exercise3/helloworld.
You should be able to build and run the project.
By the way, if you want to know which
helloworld
project you are running
(if you are running multiple of them), you can hover your mouse over
the project. (Figure-3.44 below)

Figure-3.44: Find out which directory the project is under
Summary
In this exercise, you have learned how
to add a new template to the application and how to link templates
through link_to helper.
return
to the top
Exercise 4: Build and run "helloname"
application
(4.1)
Create Ruby on Rails NetBeans project
1. Create Ruby on Rails NetBeans
project.
- Select File from
top-level menu and select New Project.
- Observe that the New Project
dialog box appears.
- Choose Ruby under Categories section on the
left and Ruby on Rails
Application under Projects section
on the right.
- Click Next.
2. Give project a name.
- For the Project Name
field, enter helloname.
- Click Finish.

Figure-4.11: Give a name to the project
return to top of exercise
(4.2)
Create database
1. Create database for the project.
- Right click helloname project
node and select Run Rake
Task->db->create. This will create helloname_development database.
return to top of exercise
(4.3)
Create model
1. Generate a model.
- Right click Models and
select Generate.
- Observe that the Rails Generator
dialog box appears.
- For the Arguments field,
enter User
name:string age:integer.
(Figure-4.31 below)
- Click OK.

Figure-4.31: Generate a model
return to top of exercise
(4.4)
Migrate the database
1. Right-click the
helloworld project
node and choose
Migrate Database >
To Current Version. This will create
users database table.
return to top of exercise
(4.5)
Create a Controller
1. Generate Controller
- Right click the Controllers node
and change Generate.
- Observe that the Rails Generator
dialog box appears.
- Enter Hello
in the Name field. Leave the Views field blank.
- Click OK. (Figure-4.51
below)

Figure-4.51: Generate controller
2. Add an action to the controller.
- Add the respond action
as shown in Code-4.52 below. The code fragment
that needs to be added is highlighted bold and red-colored font.
The respond action creates a new User
object from the input parameters
and assigns it to the @user
instance variable. It then saves it to the database
table.
class HelloController <
ApplicationController
def
respond
@user = User.new(params[:user])
@user.save
end
end
|
Code-4.52: respond action is added to the HelloController

NetBeans tip: For generating code
template for
def .. end code
block, type
def and press tab
key.
return to top of exercise
(4.6)
Write templates
1. Create index.html.erb.
- Right click Views->hello
and select New->ERB File.
- Observe that the New ERB File dialog box appears.
- For the File Name field, enter index.html.
(Figure-4.61 below)
- Click Finish.

Figure-4.61: Create index.html.erb file.
2. Modify IDE generated
index.html.erb
file as shown in Code-4.62 below. The code fragment that needs to
be added is highlighted in bold and red-colored font. The
:user respresents a
User model class and the
:name and
:age represent attributes of the
model class.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
<%
form_tag :action=>'respond' do %>
<p>
<label>Enter your name:<br/>
<%= text_field :user, :name %>
</label>
</p>
<p>
<label>Enter your age:<br/>
<%= text_field :user, :age %>
</label>
</p>
<p><%= submit_tag 'Submit' %> </p>
<%
end %>
|
Code-4.62: Modified index.html.erb

NetBeans tip: For generating code
template for the
<% form_tag
:action=>'respond' .. do %> code block, type
ft and press tab key. For
<% ... %>, type
r and press tab key.
3. Create
respond.html.erb.
- Right click Views->hello
and select New->ERB File.
- Observe that the New ERB File
dialog box appears.
- For the File Name field,
enter respond.html.
- Click Finish.
4. Modify IDE generated
respond.html.erb
file as shown in Code-4.64 below.
The code fragment that needs to be added is highlighted in bold and
red-colored font.
<%#
# To change this template, choose Tools | Templates
# and open the template in the editor.
%>
My name
is <%= @user.name %>
<br/>
My age is
<%= @user.age %>
|
Code-4.64: Modified respond.html.erb
return to top of exercise
(4.7)
Set the URL routing and delete index.html
1. Add a URLrouting.
- Expand Configuration.
- Double click routes.rb
to open it in the editor window.
- Uncomment the line #28 (in the picture below - it could be
different line number in your case) and change "welcome" to "hello" as shown in Figure-4.71 below.

Figure-4.71: A new route
2. Delete index.html under Public directory.
- Right click index.html
under Public node and select Delete.
- Click Yes if you get a confirmation dialog box.
3. Save all changes.
return to top of exercise
(4.8)
Build and run the application
1. Run the application.
- Right click helloname project
node and select Run.
- Enter your name and age into the blank fields.
- Click Submit button. (Figure-4.81 below)

Figure-4.81: Enter values into the input form fields.
- Observe that your name and age are displayed. (Figure-4.82
below)

Figure-4.82: Name and age are displayed
Trouble-shooting:
If you see the following error condition, just
refresh the page again.

Figure-4.83: Error condition

Trouble-shooting: If you see the
following error condition as shown in Figure-4.84 below, it is highly
likely because you have used the params incorrectly as shown Code-4-85
below. Correctly use it as shown in Code-4.86 below.

Figure-4.84: Error when you did not performed the database migration
This is an incorrect way of using params.
class HelloController <
ApplicationController
def respond
@user = User.new(@params[:user])
@user.save
end
end
|
Code-4.85:
Incorrectly
used params
This is a correct way of using params.
class HelloController <
ApplicationController
def respond
@user = User.new(params[:user])
@user.save
end
end
|
Code-4.86: Correctly used params
return to top of exercise
Solution
The solution of this exercise is provided as a ready-to-build NetBeans
project -
<LAB_UNZIP_DIR>/rails_basics/solutions/exercise4/helloname.
You should be able to build and run the project. (After opening
the project, you still have to create the database as described in
step 4.2 above and the migrate the database
described in
step 4.4 above before you
run the application.)
Summary
In this exercise, you have learned how
to display input form fields using form_tag
helper. You also learned how to access the values of input form
parameters.
Homework
Exercise (for people
who
are taking Sang Shin's "JRuby on Rails Development online course")
1. The homework is to write your own
simple Rails application as following (something very similar to
helloname application above).
- Name the project as studentapp.
- Create a Model called Student.
The Student model has the following fields:
- name (string type)
- age (integer type)
- Create two templates
- ask.html.erb - ask the student his/her name and age
- answer.html.erb - display the student's name and age
- When the application is run, the ask.html.erb template is
displayed
- Zip file of the the studentapp
NetBeans project. (Someone else
should be able to open and run it as a NetBeans project.) You can
use your favorite zip utility or you can use "jar" utility that comes
with JDK as following.
- cd <parent directory that contains studentapp
directory>
(assuming you named your project as studentapp)
- jar cvf studentapp.zip studentapp (studentapp should contain nbproject directory)
- Captured output screen -
name it as RailsHomework-rails_basics.gif
orRailsHomework-rails_basics.jpg (or RailsHomework-rails_basics.<whatver
graphics format>)
- Any screen capture that shows that your program is working is
good enough.
Homework
Exercise (for people
who
are taking "Real-World Technologies: NetBeans GUI, JRuby, JavaFX, ...")
1