3. Introduction
• Rails are a web application development framework written in Ruby.
• It is designed to make programming web applications easier by making
assumptions about what every developer needs to get started.
• If you learn “The Rails Way” you’ll probably discover a tremendous
increase in productivity.
• The Rails philosophy includes several guiding principles:
– DRY- “Don’t Repeat Yourself” suggests that writing the same code over and
over again is a bad thing.
– Convention over Configuration- means that Rails makes assumptions about
what you want to do and how you’re going to do it.
– REST is the best pattern for web application- organizing your application
around resources and standard HTTP verbs is the fastest way to go.
4. The MVC Architecture
At the core of Rails is the Model, View, Controller architecture, usually
just called MVC. MVC benefits include:
– Isolation of business logic from the user interface
– Ease of keeping code DRY
– Making it clear where different types of code belong for easier
maintenance
Models
A model represents the information (data) of the application and the
rules to manipulate that data. In the case of Rails, models are primarily
used for managing the rules of interaction with a corresponding
database table
5. Contd..
Views
• Views represent the user interface of your application.
• In Rails, views are often HTML files with embedded Ruby code that
perform tasks related solely to the presentation of the data.
Controllers
• Controllers provide the ‘glue’ between models and views.
• In Rails, controllers are responsible for processing the incoming
requests from the web browser, interrogating the models for data,
and passing that data on to the views for presentation.
6. Components of Rails
• Rails ship as many individual components.
• Action Pack
– Action Controller
– Action Dispatch
– Action View
• Action Mailer
• Active Model
• Active Record
• Active Resource
• Active Support
• Railties
7. REST
• Rest stands for Representational State Transfer and is the
foundation of the RESTful architecture.
• REST in terms of Rails boils down to two main principles
– Using resource identifiers such as URL’s to represent
resource.
– Transferring representations of the state of that resource
between system components.
• For example, DELETE /photos/17
8. Creating New Rails Application
Installing Rails
• gem install rails
• rails –v
Creating the Blog Application
• rails new blog
• cd blog
9. File/Folder Purpose
app/
Contains the controllers, models, views and assets for your
application. You’ll focus on this folder for the remainder of this
guide.
config/
Configure your application’s runtime rules, routes, database,
and more. This is covered in more detail in Configuring Rails
Applications
config.ru Rack configuration for Rack based servers used to start the
application.
db/ Contains your current database schema, as well as the
database migrations.
doc/ In-depth documentation for your application.
Gemfile
Gemfile.lock
These files allow you to specify what gem dependencies are
needed for your Rails application.
lib/ Extended modules for your application.
10. Contd..
File/Folder Purpose
log/ Application log files.
public/ The only folder seen to the world as-is. Contains the static files and
compiled assets.
Rakefile
This file locates and loads tasks that can be run from the command
line. The task definitions are defined throughout the components of
Rails. Rather than changing Rakefile, you should add your own tasks
by adding files to the lib/tasks directory of your application.
README.rdoc
This is a brief instruction manual for your application. You should
edit this file to tell others what your application does, how to set it
up, and so on.
script/ Contains the rails script that starts your app and can contain other
scripts you use to deploy or run your application.
test/ Unit tests, fixtures, and other test apparatus. These are covered
in Testing Rails Applications
tmp/ Temporary files
vendor/
A place for all third-party code. In a typical Rails application, this
includes Ruby Gems, the Rails source code (if you optionally install
it into your project) and plugins containing additional prepackaged
functionality.
11. Migrations
• A migration is subclass of ActiveRecord::Migration that implements two methods:
up and down.
• Active Record provides methods that perform common data definition tasks in a
database independent way.
– add_column
– add_index
– change_column
– change_table
– create_table
– drop_table
– remove_column
– remove_index
– rename_column
• If you need to perform tasks specific to your database then the execute method
allows you to execute arbitrary SQL.
• Migrations are stored as files in the db/migrate directory, one for each migration
class.
12. Contd..
• The name of the file is of form YYYYMMDDHHMMSS_create_products.rb.
• You can revert to old number scheme (2.1+) by adding following line of code in
application.rb
config.active_record.timestamped_migrations = false
• Supported types are as follows
• :binary
• :Boolean
• :date
• :datetime
• :decimal
• :float
• :integer
• :primary_key
• :string
• :text
• :time
• :timestamp
13. Creating a Migrations
• Rails generate model Product name:string description:text
• Will create a migration file
class CreateProducts < ActiveRecord::Migration
def change
create table :products do |t|
t.string :name
t.text :description
t.timestamp
end
end
end
14. Contd..
• Creating stand alone migration
rails generate migration AddPartNumberToProducts
part_number:string
• Will create a migration file
class AddPartNumberToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
end
end
15. Change Tables
• A close cousin of create_table is change_table used for changing
existing tables.
• It is used in a similar fashion to create_table but the object yielded
to the block knows more tickes.
change_table :products do |t|
t.remove :description, :name
t.string :part_name
t.index :part_number
t.rename :upccode, :upc_code
16. Special Helpers
• t.timestamps, This will add both created_at and updated_at
columns to table.
• t.references, will create appropriate foreign key column
accordingly.
t.references category => category_id
• Similarly, t.references attachment, :polymorphic => {:default
=> ‘photo’}. Will add an attachment_id column and a string
attachment_type column with a default value of “Photo”.
17. Running Migrations
• Rails provides a set of rake tasks to work with migrations which boil
down to running certain sets of migrations.
• The very first migration related task,
rake db:migrate /VERSION=version_number
• In its most basic form it just runs the up or change method for all
the migration that not yet been run or only version number
migration file if specified.
• To rollback the changes
rake db:rollback
rake db:rollback STEP=3, will run down method from last 3
migrations.
18. Schema Files
• Migrations are not the authoritative source for your database
schema.
• This role fails to either db/schema.rb or and SQL file which
Active Record generates by examining the database.
• They are not designed to be edited, they just represent the
current state of the database.
• Schema files are also useful if you want a quick look at what
attributes an Active Record object has.
19. Active Record Validations and Callbacks
• During the normal operation of a Rails application, objects may be
created, updated, and destroyed. Active Record provides hooks into
this object life cycle so that you can control your application and its data.
• Validations allow you to ensure that only valid data is stored in your
database. Callbacks and observers allow you to trigger logic before or after
an alteration of an object’s state.
Validations
• Validations are used to ensure that only valid data is saved into your
database.
• There are several ways to validate data before it is saved into your
database:
– Database constraints or stored procedures.
– Client-side validation
– Controller level validation
– Model-level validation
20. When does validation happen
• There are two kinds for active record objects
– Those that correspond to a row inside your database
– Those that do not. When you create a fresh object
• new, save, new_record?
• The following methods trigger validations and will save the object
to the database only if the object is valid:
– create
– create!
– save
– save!
– update
– update_attributes
– update_attributes!
• The save also has the ability to skip validations if passed :validate =>
false as argument.
21. Contd..
• The following methods skips the validations and will save the object
to the database regardless of its validity.
– decrement!
– decrement_counter
– increment!
– increment_counter
– toggle!
– touch
– update_all
– update_attribute
– update_column
– update_counters
• valid? and invalid? To check the validity of an object.
• errors method is used only after validation have been run.
22. Validation Helpers
• Active record offers many pre-defined validation helpers that can
use directly inside your class definitions.
• These helpers provide common validation rules. Every time a
validation fails, an error message is added to the
object’s errors collection, and this message is associated with the
attribute being validated.
• Each helper accepts arbitrary number of attributes.
23. Contd..
• The helper methods are as follows
a. acceptance
validates :terms_of_services, :acceptance => true
b. validates_associated
has_many :books
validates_associated :books
c. confirmation
validates :email, :confirmation => true
d. exclusion
validates :subdomain, :exclusion => {:in => %w{www us ca jp),
:message => “Sumdomain %{value} is reserved.”}
e. format
validates :legacy_code, :format => {:with => /A[a-zA-Z]+z/,
:message => “Only letters are allowed”}
24. Contd..
f. Inclusion
g. length
validates :name, :length => {:in => 2..20}
h. numericality
validates :points, :numericality => true
i. presence
validates :name, :presence => true
j. uniqueness
validates :email, :uniqueness => true
k. validates_each
validates_each :name, :surname do |record, attr, value|
record.errors.add(attr, 'must start with upper case') if value =~ /A[a-z]/
end
25. Contd..
l. validates_with
class Person < ActiveRecord::Base
validates_with GoodnessValidator, :fields => [:first_name,
:last_name]
end
class GoodnessValidator < ActiveModel::Validator
def validate(record)
if options[:fields].any?{|field| record.send(field) == "Evil" }
record.errors[:base] << "This person is evil"
end
end
end
26. Contd..
• There are common validation options:
a. :allow_nil
validates :size, :inclusion => {:in => %w{small medium large}),
:message => “%{value} is not valid”, :allow_nil => true
b. :allow_blank
validates :title, :length => {:is=>5}, :allow_blank => true
c. :message
d. :on
validates :email, :uniqueness => true, :on => create
27. Errors
• Returns an instance of the class ActiveModel::Errors containing all errors.
• Each key is the attribute name and the value is an array of strings with all errors.
• errors[] is used when you want to check the error messages for a specific attribute.
• It returns an array of strings with all error messages for the given attribute, each
string with one error message.
• errors.add method lets you manually add messages that are related to particular
attributes.
• Errors[:base] add error messages that are related to the object’s state as a whole,
instead of being related to a specific attribute.
• errors.clear method is used when you intentionally want to clear all the messages
in the errors collection.
• errors.size method returns the total number of error messages for the object.
28. Callbacks
• Callbacks are methods that get called at certain moments of an object’s
life cycle.
• With callbacks it is possible to write code that will run whenever an Active
Record object is created, saved, updated, deleted, validated, or loaded
from the database.
29. Contd..
Callback Registration
• In order to use available callbacks, you need to register them.
before_validation :ensure_login_has_a_value
protected
def ensure_login_has_a_value
if login.nil?
self.login = email unless email.blank?
end
End
• You can implement the callbacks as ordinary methods and use a macro-
style class method to register them as callback.
before_create do |user|
user.name = user.login.capitalize if user.name.blank?
end
30. Observers
• Observers are similar to callbacks, but with important differences.
• Whereas callbacks can pollute a model with code that isn’t directly related to its
purpose, observers allow you to add the same functionality without changing the
code of the model.
Creating Observers
• rails generate observer User
• generates app/models/user_observer.rb containing the observer class
UserObserver
• The observer method receive the observer model as a parameter.
class UserObserver < ActiveRecord::Observer
def after_create(model)
# code
end
End
• Observers are conventionally placed inside of your app/models directory and
registered in your application’s config/application.rb file.
config.active_record.observers = :user_observer
31. Active Record Associations
The Types of Association
Rails supports 6 types of associations
1. belongs_to
2. has_one
3. has_many
4. has_many :through
5. has_one :through
6. has_and_belongs_to_many
32. Contd..
belongs_to Associstion
• A belongs_to association sets up a one to one connection with
another model, such that each instance of the declaring model
“belong to” one instance of the other model.
33. Contd..
has_one Association
• This association indicates that each instance of a model contains or
possesses on instance of another model.
38. Layouts and Rendering
Creating Responses
• From controller point of view, there are three ways to create an
HTTP responses:
• Call render to create a full response to send back to the browser.
• Call redirect_to to send an HTTP redirect status code to the
browser.
• Call head to create a response consisting solely of HTTP headers to
send back to the browser.
39. Contd..
• Rendering by Default: Convention over Configuration
• Using render
• Render Nothing
render :nothing => true
• Render an Action view
If you want to render the view that corresponds to a different
action within the same template.
• Rendering actions Template from another controller
render ‘products/show’ or render :template =>
‘products/show’
• Rendering an Arbitrary file
render :file => ‘apps/warehouse/app/views/products/show’
By default, the file is rendered without using the current
layout. If you want rails to put the file into the current layout, you need
to add the :layout =>true option.
40. Contd..
• Using render with inline
render :inline => “<% products.each do |p|
%><p><%=p.name%></p><%end%>”
• Rendering Text
render :text => “OK”
By default, the file is rendered without using the current layout. If
you want rails to put the file into the current layout, you need to add the
:layout => true option.
• Rendering JSON
render :json => @product
• Rendering XML
render :xml => @product
• Rendering Javascript
render :js => “alert(‘Hello world!’);”
41. Finding Layouts
• To find the current layout, Rails will first looks for a file in
app/views/layouts with the same base name as the controller.
• If there is no such controller-specific layout, Rails will use
app/views/layouts/application.html.erb or
app/views/layouts/application.builder. If there is no .erb layout,
Rails will use a .builder layout if one exists.
• Rails also provides several ways to more precisely assign specific
layouts to individual controllers and actions.
class CustomController < ActionController::Base
layout “custom”
end
42. Using redirect_to
redirect_to photos_url/:back
Asset Tag Helpers
• Asset tab helpers provide methods for generating HTML that link
views to feeds, javascript, stylesheets, images, videos and audios.
• There are six asset tag helpers available in Rails:
– auto_discovery_link_tag
– javascript_include_tag
– stylesheet_include_tag
– image_tag
– video_tag
– audio_tag
43. Action Controller
Methods and Actions
• A controller in a Ruby class which inherits from
ApplicationController and has methods just like any other class.
• When your application receives a request, the routing will
determines which controller and action to run, then Rails creates an
instance of that controller and runs the method with the same
name as the action.
class ClientsController < ApplicationController
def new
end
end
44. Parameters
• You will probably want to access the data sent by the user or other
parameters in your controller actions.
• There are two types of parameters
– Query string parameters
– POST data
• These parameters are accessible from params.
• Hash and Array Pararmeters
• JSON/XML Parameters
• Routing parameters
• ##002#
45. Session
• Application has a session for each user in which you can store small
amounts of data that will be persisted between requests.
• The session is only available in the controller and the view and the view
and can use one of the different storage mechanisms:
– ActionDispatch::Session::CookieStore – Stores everything on the client
– ActiveRecord::SessionStore – Stores in database using ActiveRecord.
– ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.
– ActionDispatch::Session::MemCacheStore – Stores the data in a memcached
cluster.
• All session stores use a cookie to store a unique ID for each session.
• This ID is used to lookup the session data on the server.
• The CookieStore can store around 4kB of data much less then the others
but this is usually enough.
• If you need a different session storage mechanism, you can change it in
the
config/intializers/session_store.rb file
YourApp::Application.config.session_store :active_record_store
46. Accessing the session
• In controller the sessions can be accessed through the
session instance method.
• Session values are stored using key/value pairs like a hash
class ApplicationController < ActionController::Base
private
def current_user
@current_user ||= session[:current_user_id] &&
User.find(session[:current_user_id])
end
end
47. The flash
• The flash is a special part of the session which is cleared with each
request.
• This means that values stored there will only be available in the
next request, which is useful for storing error messages etc.
• It is accessed in much the same way as the session.
def destroy
session[:current_user_id] = nil
flash[:notice] = “You have been logged out successfully”
redirect_to root_url
End
• By default, adding values to flash makes them available to the next
request, but sometimes you may want to access those values in the
same request.
48. • Filters
• Filters are methods that are run before, after or around a controller action.
• Filters are inherited, so if you set a filter on ApplicationController, it will be run on
every controller in your application.
• A common before filter is one which requires that a user is logged in for an action
to be run.
class ApplictionController < ActionController::Base
before_filter :require_login
private
def require_login
unless require_login?
flass[:error] = “You must be logged to access this section”
redirect_to new_login_url
end
end
def logged_in?
!!current_user
end
end
49. Contd..
• In addition to before_filters, you can also run filters after an
action has been executed, or both before and after.
after_filter :method_name
around_filter :method_name
50. Routing
• The rails router recognizes URLs and dispatches them to a
controllers action.
• It can also generate paths and URL’s, avoiding the need to
hardcode strings in your views.
• When Rails application receives an incoming request
GET /patients/17
• It asks the router to match it to a controller action. If the first
matching route is
match “/patients/:id => “patients#show”
51. Resource Routing
• Resource routing allows you to quickly declare all of the common
routes for a given resourceful controller.
• Instead of declaring separate routes for your index, show, new, edit,
create, update and destroy actions.
• A resourceful declares them in a single line of code.
Resources :photos
• In Rails, a resourceful route provides a mapping between HTTP
verbs and URLs to controller actions.
• By convention, each action also maps to particular CRUD operations
in a database.
52. Contd..
HTTP Verb Path action used for
GET /photos index display a list of all photos
GET /photos/new new return an HTML form for
creating a new photo
POST /photos create create a new photo
GET /photos/:id show display a specific photo
GET /photos/:id/edit edit return an HTML form for
editing a photo
PUT /photos/:id update update a specific photo
DELETE /photos/:id destroy delete a specific photo
53. Contd..
• Creating a resourceful route will also expose number of helpers to the controller in
your application. In the case of resources :photos
– The photos_path => /photos
– The new_photo_path => /photos/new
– The edit_photo_path(:id) => /photos/:id/edit
– The photo_path(:id) => /photos/:id
• The groups of controller can organized in under a namespace. Most commonly, the
number of administrative controllers are grouped under an Admin::namespace.
– This will create a number of routes for each of the posts and comments
controller for
Admin::PostsController.
namespace :admin do
resource :posts, :comments
end
– To route /posts to Admin::PostsControllers
resources :posts, :module => “admin”
– To route /admin/posts to PostsConroller
resources :posts, :path => “admin/posts”
54. Contd..
• Multiple resources can be defined in either of the two ways
– resources :photos, :books, :videos
– resources :photos
resources :books
resources :videos
• Its common to have resources that are logically children of other resources (Nested routes)
resources :magazines do
resources :ads
end
• This is not limited to seven routes that RESTful routing creates by default. You may add
additional routes that apply to the collection or individual members of the collections.
– To add member routes
resources :photos do
member do
get “preview”
end
End
– To add collection routes
reourcees :photos do
collection do
get “search”
end
end
55. Non Resourceful Routes
• Rails has powerful support for routing arbitrary URL’s to actions.
• Here, the groups of routes are not automatically generated. Instead, you setup
each route within your application separately.
Bound Parameters
match ‘:controller(/:action(/:id))’
The series of symbols that Rails maps to parts of an incoming HTTP requests
Dynamic Segments
match ‘:controller/:action/:id/:user_id
You can set up as many dynamic segments with a regular route as you like.
The Qurey String
Defining Defaults
match ‘photos/:id’ => ‘photos#show’
Naming Routes
match ‘exit’ => ‘sessions#destroy’, :as => :logout,
This creates logout_path and logout_url as named helpers in your application.
56. HTTP Verb Constraints
• You can use the :via option to constraint the request to one or more HTTP
methods
match ‘photos/show’ => ‘photos#show’, :via => :get
• You can also permit more than one verb to a single route
match ‘photos/show’ => ‘photos#show’, :via => [:get, :post]
Segment Constraints
• The :constraints option enforce a format for a dynamic segment
match ‘/photos/:id’ => ‘photos#show’, :constraints => {:id => /[A-Z]d{5}/
• The above route would match paths such as /photos/A12345.
Route Globbing
• Route globbing is a way to specify that a particular parameter should be matched
to all the remaining parts of a route.
match ‘photos/*other’ => ‘photos#unknown’
• This route would match /photos/12 or /photos/long/path/to/12. Setting
params[:other] to “12” or “long/path/to/12”.
57. ERB Templating
• The ERB is the feature of Ruby that enables you to conveniently generate any kind
of text, in any quantity, from templates.
• The templates themselves combine plain text with Ruby code for variable
substitution and flow control, which makes them easy to write and maintain.
• Although ERB is commonly seen generating web pages, it is also used to produce
xml documents, RSS feeds, source code and other forms of structured text file.
• The main component of ERB is a library which you can call within your Ruby
applications and rake tasks.
• This library accepts any string as a template, and imposes no limitations on the
source of the template.
• The definition of a template can be entirely within your code or store it in an
external location and load it as required.
• Ruby distributions also includes command line utility that enables you to process
templates that are held in files without writing ay additional code. This utility is
called erb.
58. Writing Templates
• ERB copies the text portions of the template directly to the
generated document, and only processes code that is identified by
markers.
• Most ERB templates only use a combination of two tag markers,
each of which cause the enclosed code to be handled in a particular
way.
• A tag with an equals sign indicates that enclosed code is
an expression, and that the renderer should substitute the code
element with the result of the code (as a string) when it renders the
template.
Hello, <%= @name %>
Today is <%= Time.now.strftime(“%A”) %>
59. Contd..
• Tags without the equals sign denote that the enclosed code is a scriptlet
<ul>
<% for @item in @shopping_list %>
<li><%= @item%></li>
<% end %>
</ul>
• By default , a newline character is added to the page after the position of
each tag. To suppress this newline. To suppress the newline add hyphen
to the trailing tags in Rails template.
• A file that contains an ERB template may have any name, but it is the
convention that the name of file should end with the .erb extension.
• Rails requires template files to have the extension of the output type,
followed by .erb, so that a name like layout.html.erb indicates a
HTML template.
60. Using erb library
• This is very simple example
require ‘erb
@weekday = Time.now.strftime(“%A”)
simple_template = “Today is <%=@weekday %>.”
Renderer = ERB.new(simple_template)
puts output = renderer.result()
• ERB only processes the template when result is called.
• This means that the output will show the values of variables as they are at
the moment when the result is rendered, not when the ERB object was
defined.
61. Running erb in a Sandbox
• You may protect your application from ERB by running it in a new
thread.
renderer = ERB.new(template, 3)
• The third parameter of new specifies optional modifiers, most of
which alter when newline characters will be automatically added to
the output. For example, ERB will not print newlines after tags if
you give > as the third parameter.
renderer = ERB.new(template, 3, ‘>’)
62. Running erb on commandline
• The erb utility processes a given template and sends the result to
the standard output.
erb my-template.txt.erb > new-file.txt
• The template can automatically use built-in Ruby classes, such
as String and File.
• To allow it to access standard or third-party libraries, use the -
r option. This option works in the same way as the require keyword.
• The below example processes a template that uses Abbrev and
IPAddr libraries
erb –r abbrev –r ipaddr my-template.txt.erb > new-file.txt
• Use the –S option to specify a safe level that isolates the template
processing.
erb –S 3 my-template.txt.erb > new-file.txt