draft - IBM

arrogantpreviousInternet και Εφαρμογές Web

2 Φεβ 2013 (πριν από 5 χρόνια και 4 μήνες)

296 εμφανίσεις

Chapter 6.

Understanding Rails

(35 pages)

Understanding Rails: The big picture


Directory Structure

When you use the “rails” command to create a rails application it automatically generates a basic directory structure. Rails
doesn't need to speci
fy anything, it knows where to find everything. Each directory has its own purpose. Let's take a look at
some of the most important directories and files.

@TODO: change it with a better picture and with the example application.


As rails is web
cation framework that implements the MVC pattern (we will see it later),

directory holds all the files
related to this pattern. It splits the application in three layers: models, views and controllers.

directory are

all the models classes.
They should be named like
and most of them will descend


directory are all the template files for each view and they should be named like
. There is a
directory inside vi
ews directory, it holds the template files for layouts
to use with views. Layouts define header/footer method of wrapping views.


we'll find the the controller classes, they should be named like
controller name_controller.rb
. All controllers
should descend from

which itself descends from

There is also a

directory which contains helper classes that should be named like
. Helpers will
help us assisting our views and wrapp
ing functionality from the views into methods.


It holds all the configuration files that rails need. It includes database configuration (
), rails environments
configuration (
) and different configuration for each environme
nt (the default environments are

). There is also an important file that
defines the routing map (


It contains the database schema definition (
) and al
l the migrations for the schema (



There are the log files for each environment. If anything goes wrong you'll be able to inspect your application log files or
watch it in real time with "
” in the



This directory is available for the web server. All the static contents are in this directory: stylesheets, javascript files,

html files, etc. It's the DOCUMENT_ROOT or the web server.


It holds the units, the functional test and th
eir fixtures. Here you can create your test or modify all the tests that are created
when you use any of



In this directory are all the external libraries that the application depends on. If you freeze rails, those gems will
be copied
here under
. This directory is in the load path.


In the application development process, it's useful to have different settings depending on the environment where you're
working on. For example when you're adding new fun
ctionality, you would like to see it in the development environment
previously to change it in production environment. Or if you are in production mode, it's not necessary to reload classes on
each request, cause they are not going to change periodically,
so it speeds up the application response. Or even when you
are running tests, you would like to do them against a special database for testing instead of production database.

For all those things, Rails allows you to setup different environments for each a
pplication. Rails creates three environments
by default: development, test and production. You can create new environments or modify the existent ones. To modify or add
settings to the environments you can do it in the config/environment.rb file. These cha
nges will affect to every environment.
But each environment has its own configuration file in config/environments/*.rb. Everything you write on them will overwrite
settings on environment.rb file.

Several processes read the environment.rb file like the web
rick server, the console, etc. At this point, even rails is loaded. So
you can specify the rails gems version on it with the option:


Let's open the file config/environment.rb and review some of the settings inside of it.

All s
ettings except
RAILS_GEM_VERSION should be specified inside the Rails::Initializer.run block. An instance of
Rails::Configuration is passed to the block and assigned to the config variable. With it, you can change any attribute of
configuration. Some of th
em are:

, you can remove some frameworks if you don't need them, just to enhance the performance, for example if
you don't use actionmailer and activeresource you can remove them by:

= [ :active_record, :active_resource, :actio
n_mailer ]

, you can specify which gems the application depends on, and if you don't have them you can install them running
the rake task “gems:install”. For example:

config.gem "hpricot", :version => '0.6', :source => "

config.gem "sqlite3
ruby", :lib => "sqlite3"

, it is the log level to use for the Rails logger. In production mode the default is :info, in development mode it's

config.log_level = :info

To see more settings, please visit the


MVC Architecture

Ruby on Rails is organized in the Model
Controller (
MVC) architecture. And for that reason, Rails divides the application
in three different layers: application’s data and functionality (Model), user interface (View), and control logic (Controller
), with
a minimal dependency among them.

With this, it's poss
ible to isolate the business logic from the user interface. So if you need to change the application
appearance or any of its business rules, it could be done easily without affecting each other.

Picture of MVC.


are responsible of the application

business logic. They deal with the data and rules. In Rails a model represents a
database table, the relationships with other models, the validation rules and everything related with business. Rails uses
ActiveRecord to do it.


are responsible for th
e user interface. In Rails they are files that contains HTML code together with embedded ruby
code (erb), the last one manipulates the data that is provided by the model.


are the intermediary between views and model. A controller performs the r
equest action, then obtains the
necessary from the model and sends it to the action view.

@TODO: I would like to explain the entire workflow of a request with an example (of the application example).

IMAGE of Rails MVC (including routing)


I will men
tion what is ActiveRecord and “Active Record” pattern.

Also the main features of AR (in some cases with samples of our application):

Associations (It will cover in the next chapter)

Validations (some basic validation helpers),

Finding records (.first, .al
l, .find with:conditions, order, limit)

Updating and deleting records.

Calculations(maximum, sum, count, average)

Dynamic finders


In order to get help from the console, I will show how to use “script/generate model” command (maybe I'll show
screenshot of the command output).

I'll explain how to create a simple model of our example application.

Naming Convention

I will show how ActiveRecord uses CoC including:

Automated mapping between classes and tables, attributes and columns.


Associations(primary keys and foreign keys)

Automated Record Timestamps


I will explain the different types of templates, erb (.rhtml), builder (.rxml), JavaScriptGenerator (.rjs)

Working Embedded

I will start explaining how to mix ruby code and html

using <% %>, <%
%>, and <%= %> (some samples with
iterators or conditionals within html code).

Forms, Layouts and Helpers

Creating forms

I will explain how to create a form based in a model with form_for (explaining the difference between form_for
and fo
rm_tag). How it works when we submit it (params) and what happened if validations returns some errors.

I'll describe form inputs methods (text_field, label, text_area, check_box, submit_tag,)

Should I mention “fields_for” method? (for an additional model o
bject inside the form)

Sharing code with helpers

I'd like to highlight reasons to use helpers (duplication of code, share functionality, etc)

Also how to create a helper, how to use it in a view and share it to another controller's views.

Working with layo

I'll explain the reasons to use layouts (header, footers) (DRY); how they are rendered, the yield method, how to
pass data to layouts (title example) and how to specify a different layout.



In order to get help from the console, I

will show how to use “script/generate controller” command (maybe I'll
show a screenshot of the command output).

Also how to create a simple controller of our example application.

Linking the three

I'll explain why controllers are the core of web requests.

The relationship among the request, the controller's action and the template renderization (populating an
instance variable from model and passing it to the default template or a specific template).

I'll mention how to access to parameters, the respond_
to method, how to move to another action with redirect_to
and how to send messages with Flash object.

Should I talk about Sessions and Cookies?

Should I talk about filters?

RESTing with Rails

A simple description of REST.

I'll describe how to create RESTfu
l routes (and then run the rake routes task to see them)

I'll mention the seven actions of a restful controller (index, create, new, show, update, edit and destroy)

Should I talk about additional actions?

Should I talk about nested resources?

Static and D
ynamic Pages

I'm not sure if I understood this point.

Differences between static and dynamic pages?

How to create a static page in rails?





Review Questions



Naming Convention


Working Embedded

Layouts and Helpers

Creating forms

Sharing code with helpers

Working with layouts



Linking the three

RESTing with Rails

Static and Dynamic Pages



Review Questions