To Lecture Notes
IT 231 -- 7/23/12
Review Questions
- How do you create a DOS batch file?
Ans: Create a .txt file and change the file extension to .bat.
- What does ERB mean?
Ans: ERB means embedded Ruby (embedded within an HTML file)
Place embedded Ruby code within the ERB delimiters
<%= ... %>
ERB files have the file extension .html.erb
- What is the Rails helper function to
display an image? Ans: image_tag
link to a stylesheet? Ans: stylesheet_link_tag
implement a hyperlink? Ans: link_to
- You enter the following URL in a browser, but the corresponding page does
not display properly. List some things that might be wrong?
http://localhost:3000/Info/index
Ans:
- You might have saved the view or layout properly.
- You might not have started the server.
- You didn't wait long enough for the server to startup before
viewing the page.
- You didn't convert the controller name to underscore notation before
trying to use it as a URL.
- The controller name in the URL includes an uppercase letter.
- You don't have a proper end title tag.
- You are missing an ending ERB delimiter.
- What is the difference between these variables?
title @title
Ans: title is a local variable only valid in the method where it is
used; @title is an instance variable valid for the duration of the
application. Use instance variables for embedded Ruby code placed
on a webpage.
- You have already added a new controller named Info with its views and
entered their content. However, you realize that you have forgotton to
add the view called page1. What are the steps for adding a
new view to the existing controller?
Ans:
- Add a new view named in app/views/info/page1.html.erb
- Add a new method named page1 in app/controllers/info_controller.rb. The
new page1 method might look like this:
def page1
@title = 'Page 1'
end
- Add the following new route to app/config/routes.rb:
get "info/page1"
- What is wrong?
rails new generate controller A index p 1
Ans: The word new should not be here and there should not be a space between
p and 1 because actions cannot contain spaces. The scaffold software will
think that the actions are index, p, and 1, but 1 is not a legal name for
an action.
- What is wrong?
rails scaffold generate People name:int gender:Text class:String
Ans: The words scaffold and generate should be reversed. Optionally, you
can abbreviate generate to g. The model name People should
be singular (Person), int should be string, text should be
string and lower case because the gender is only
one letter. Even if you want to use an integer, spell out the datatype as
"integer", not "int". class is a reserved word, so use another word
like course instead, string should be lower case.
- What are some possible datatypes for a Rails scaffold?
Ans: :string, :text, :integer, :double, :decimal, :boolean, :date,
:time, :datetime.
- Write a Rails generate scaffold statement to manage student objects
with fields name, major, year, and gpa. Ans:
rails g scaffold Student first_name:string major:string year:integer gpa:float
- What does rake db:migrate do?
Ans: Uses the migration configuration file in db/migrations to create
the database and ActiveRecord helper functions.
- In Rails, when do you use upper camel casing and when do you use
underscore notation?
Ans: You use upper camel casing for the project name and controller name
in rails command prompt comments. Use camel casing also for names of
Rails classes, such as
the model name and the controller class name. You use underscore notation
for pretty much everything else (e.g., controller folder name for views,
controller file name, view file names, view names in rails commands, route
specification, URLs).
- What is the name and location of the underlying database for a Rails
project generated using a scaffold?
Ans: db/development.sqlite3
- Which views does the Rails scaffold software create?
Ans: index, show, new, view.
- How do you determine the controller and action to use to display
a Rails view by looking at the Rails project?
Ans: Look in app/views. You will find a folder named layouts and another
folder. The other folder is the controller name. Go into this folder
the .html.erb files in this folder correspond to the names of the views.
- How can you tell if a Rails website has been created by using the
generate scaffold command?
Ans: Look in app/views. Then go into the folder with the name of the
controller. If the view names are index, show, new, and edit, with another
file named _form.html.erb, it is very likely that the project was created
with the Rails scaffold software.
- How does a view know (a) if it is supposed to use a layout page and
(b) which layout page to use?
Ans: (a) A view indicates that it wants to use a layout page if there is either
a file named <controller_name>.html.erb or application.html.erb in
app/views/layouts. (b) If both files are present, the one with the controller
name is used. Of course, the layout page must contain the ERB statement
<%= yield %>
for the layout page to work.
Resizing an Image with MS Paint
- Right click on image name in MS Explorer
- Select Open with ... >> MS Paint.
- Resize Image.
- Set the horizontal and vertical boxes to a percentage less than
100 to shrink the image.
(Reducing the side of an image by a factor of
f reduces the area by about f squared.)
- Save the image.
Projects Created by the Rails Scaffold Software
This statement does the following:
- creates a controller,
- creates these views: index, show, new, edit,
- creates the specs for the database fields,
Now enter the rake statement to create the actual database
and database table:
rake db:migrate
The following names are created:
| Resource Name | movie_reviews |
| Database Table Name | movie_reviews |
| Model Name | MovieReview |
| Controller Name | MovieReviewController |
| View Folder Name | movie_reviews |
| URL | http://localhost:3000/movie_reviews |
Note which names are written upper camel notation and which others are
written in underscore notation.
The Rails scaffolding software knows how to pluralize the name that
represents table rows. In this case, Person represents the name of
a single row and People represents the entire collection of rows
in the table.
Here are the names generated by scaffold if the model name is
Person:
| Resource Name | person |
| Database Table Name | people |
| Model Name | Person |
| Controller Name | PersonController |
| View Folder Name | people |
| URL | http://localhost:3000/people |
Warning: Rails does not know how to pluralize every noun with an
irregular plural. For Rails, the plural of sheep is sheeps. The
plural of goose is gooses.
Student is the name of the model.
Remember that the datatypes in a generate scaffold statement are
case sensitive.
Caution: stay away from Rails reserved words, both for the model
name and for the field names within the model. Here is a website that
lists Rails reserved words:
Look at the file with a name similar to
db/migrate/20110404234401_create_students.rb
This is the migration file that contains the database schema.
Now run the migration file with
rake db:migrate
This creates the database and schema in
db/development.sqlite3
and
app/db/schema.rb
respectively.
Sites created with the scaffold software implement the
CRUD applications. CRUD means Create, Read, Update, Delete.
Start the Rails server and enter some students into the
students database table.
Use the Rails dbconsole to examine the contents of the database.
- Shut down the Rails server.
- Start the database console with
rails dbconsole
- Enter
.tables
to see the names of all the tables in the database.
- Enter the SQL statement
select sql from sqlite_master where name = 'students';
to see the the SQL command that was used to create the students table.
- Enter the SQL statement
select * from students;
to see the contents of the students table.
- Enter .exit to exit the dbconsole.
Use the Rails render statement to include Rails view code from
another file.
A Rails scaffold project uses the render statement to include
the code in the _form.htm.erb file in both the new and edit views.
Code included in a form using a render statement is
called a partial view or a partial for short.
Modifying the Dropdown Menus for Selecting a Date
to
f.date_select :birth_date, :start_year => 1983, :end_year => 2015
Caution: 1983 and 2015 must not be in quotes because they are integers, not
strings.
Here are some other options for f.date_select:
# Use month numbers instead of names.
:use_month_numbers => true
# Add month numbers in addition to names.
:add_month_numbers => true
# Use short form of months: Jan, Feb, Mar, ...
:use_short_month => true
# Don't include a dropdown menu for days.
:discard_day => true
# Don't include a dropdown menu for months.
:discard_month => true
# Don't include a dropdown menu for years.
:discard_year => true
Validations
- When a value of the wrong datatype is placed into a model,
no error message is given.
- For example, if a non-numeric string value is placed into an
integer field, it will silently converted to 0.
- Validations allow a Rails project to show error messages
when illegal values are entered into fields.
- Validations are placed into the body of the model in app/model.rb.
Here are some examples of older Rails validations:
validates_presence_of :first_name
validates_length_of :student_id,
:minimum => 4, :maximum => 4
validates_numericality_of :gpa,
:greater_than_or_equal_to => 0.0,
:less_than_or_equal_to => 4.0,
:only_integer
Here are some examples using the modern Rails validations:
validates :title, :presence => true
validates :email, :uniqueness => true
validates :username, :length => { :within => 8..20 }
validates :age, :numericality => true
validates :age, :numericality => { :only_integer => true }
validates :age, :numericality => { :greater_than => 0 }
Some Rails documentation recommends using the older forms
validates_presence_of, validates_length_of, and validates_numericality_of
instead of the modern form validates.
Project 2
Moving Web Pages over the Internet
- In the early days of computer networking (pre 1969), connections
between computers were hardwired, and the software to implement the connection
was custom tailored to the operating systems of
the connected computers.
- As the ARPANET (predecessor of the modern
Internet) was being built, it became clear that connecting a large
number of computers together in one large network required a well
designed network architecture.
- Gradually the Open Systems Institute (OSI)
Seven Layer Model was developed, starting in 1977.
- This Seven Layer Model was used to organize network software and
allow a wide variety of computer network systems to be connected
into a single network.
- Of special interest is the HTTP software, which sits at the very top
of the Seven Layer Model in the Application layer.
- Modern telecommunications systems send data in relatively small packets
over the best available transmission line. Then the packets are
collected and reassembled to present to the application software
on the destination machine.
- See this document for a taste of HTTP in the early days:
Running WEBrick on a Different Port
- To start Webrick on a different port:
rails server --port=5000
Then use this URL:
http://localhost:5000/grocery_items
The default port for HTTP is 80. If WEBrick is started as
rails server --port=80
then the page can be viewed without specifying a port number:
http://localhost/grocery_items
Two Rails servers running at the same time on the same machine must
run on different ports.
Here is a list of some other
well-known ports.
Well-known ports are in the range from 0 to 1023.
Know the port number usually associated with HTTP, which is 80.
HTTP GET vs. POST
Submit information via HTTP POST:
The page information is not submitted back to the server
in the URL; it is submitted in the page head.
Representational State Transfer
- Representational state transfer (REST) means using
the HTTP commands GET, POST, PUT, and DELETE operations to implement
the CRUD operations:
- REST also assumes
- use of a client-server architecture
- stateless communication, which means that the neither the views nor the
controller remembers the contents of previously submitted pages.
- Defining the following route in config/routes.rb creates the
entire set of CRUD operations:
map.resources :items
Some details of REST
operations, when the resources are defined as :items.
Five Ways to Execute Ruby Code
- Using Interactive Ruby
In a Command Prompt Window, type irb for Interactive Ruby.
Then enter the Ruby statements as shown:
C:\>irb
irb(main):001:0> c = 20
=> 20
irb(main):002:0> f = 9 * c / 5 + 32
=> 68
irb(main):003:0> print "The Celsius temperature is ", c, ".\n"
The Fahrenheit temperature is 20
=> nil
irb(main):003:0> print "The Fahrenheit temperature is ", f, ".\n"
The Fahrenheit temperature is 68
=> nil
irb(main):003:0> puts "The Celsius temperature is " + c.to_s + "."
The Fahrenheit temperature is 20
=> nil
irb(main):003:0> puts "The Fahrenheit temperature is " + f.to_s
The Fahrenheit temperature is 68
=> nil
Enter ^C to exit irb.
The items to print in a print statement are listed sequentially,
separated by commas. To go to a new line, an explicit new line character
\n must be used.
Although normally a string can use either single or double quotes,
for a \n to be interpreted as a new line character, double quotes must be
used.
In single quotes, \n is interpreted as a backslash and a letter n. Only
in double quotes is \n interpreted as a new line character.
The Ruby method puts prints a single string. If multiple items are to
be displayed with puts, they must be concatenated together in a single
string using the concatenation operator +.
- Executing Ruby commands from an .rb file
Use JEdit to create a Ruby file named ex1.rb that contains the following
Ruby statements:
c = 20
f = 9 * c / 5 + 32
print "The Celsius temperature is ", c, ".\n"
print "The Fahrenheit temperature is ", f, ".\n"
puts "The Celsius temperature is " + c.to_s + "."
puts "The Fahrenheit temperature is " + f.to_s + "."
Save these commands and exit the Command Line Editor.
From a Command Prompt window, enter rb ex1.rb. You should get
output as shown here:
C:\>ruby c2f.rb
The Celsius temperature is 20.
The Fahrenheit temperature is 68.
The Celsius temperature is 20.
The Fahrenheit temperature is 68.
- Using Embedded Ruby (ERB)
Create a Rails project named TestRuby.
 
Create a controller named ex1 with one page named index.
 
Add the following Ruby statements to the controller index method:
@c = 20
@f = 9 * @c / 5 + 32
Replace the HTML code in index.html.erb with this source code:
<html>
<head>
<title>Cel To Fahr Example</title>
</head>
<body>
<h1>Cel To Fahr Example</h1>
<p>Celsius Temperature: <%= @c %></p>
<p>Fahrenheit Temperature: <%= @f %></p>
</body>
</html>
- Running Ruby from the Rails Console Interactively
Enter a rails project created by the scaffold software, for example
the Census project (Example 8).
C:\> cd railsprojects\Census
C:\> rails console
Loading development environment: (Rails 3.0.5)
>>
Now you can enter Ruby commands as you did with irb. The advantage of
this context is that all of the classes defined by the scaffold software
are available.
Now enter the following commands.
p = Person.first
p.name
p.gender
p.age
p.gender = "F"
p.save
s = Person.new
s.name = 'Walter'
s.gender = 'M'
s.age = 45
s.save
Now shut down the console with ^C and start the server and check the
database with your browser to see whether
the changes actually made it to the database.
- Loading a Ruby Batch File from the Rails Console
- Enter a Rails project and create a ruby file named
update.rb with JEdit
- Enter Ruby commands similar to what you entered in
Section 4.
- Start the Rails Console as you did in Section 4.
- Load and run the Ruby file with
load 'update.rb'
Project 3