SlideShare a Scribd company logo
1 of 39
Routing
2 purposes of Routing
2 purposes of Routing
1) maps Requests to Controller Action methods
2) generation of URLs
●

To be used as arguments to methods like
link_to, redirect_to
1.) Mapping HTTP Requests to
Controller-Actions
Lifecycle of a HTTP Request
routes.rb
●

config/routes.rb
●

specify 'Routing Rules' a.k.a 'Routes' here

●

Order is important
Rules are applied in the order in which they
appear

●

To list all routes:
rake routes

●

To filter routes :
routes.rb (contd.)
NOTE
●

Whatever URLs have to work, have to be
EXPLICITLY specified in routes.rb
–

Unless the .html file exists in “public” folder

i.e. Even if we create Controller, ControllerAction, View →
if there is no route for the URL in routes.rb, then
that URL will NOT work
routes.rb (contd.)
●

A website may have many, many, URLs that
need to work…
so,
how to specify all of them in routes.rb ?

●

In routes.rb, when we create 'routing rules', we
can specify patterns for permitted URLs
(Next few slides talk about the Syntax used for
specifying those 'routing rules')
Legacy way that does Not work
●

Legacy way of supplying controller and action
parameters prior to Rails 3 does not work
anymore
# DOES NOT WORK
match 'products/:id', :controller => “product”, :action =>
“show”
Regular Syntax
●

Regular syntax
●

●

use :to

match [URL Pattern],

:to => Controller#Action

E.g.
match 'products/:id', :to => 'products#show'
ShortCut – drop “:to”
●

Full Syntax
match 'products/:id' , :to => 'products#show'

●

Shortcut
match 'products/:id' => 'products#show'

We can drop - , :to
Another Shortcut Syntax –
when path already has controller &
action names
●

Full Syntax
match “/projects/status”, :to => “projects#status”

●

Shortcut
match “/projects/status”
●

“projects” controller

●

“status” action
Constraining Request Methods
and Shortcut
●

To limit the HTTP method :via parameter
match 'products/show', :to => 'products#show', :via

●

Shortcut:
get “/products/show”

=> :get
Segment Keys
●

match 'recipes/:ingredient' => “recipes#index”

“:ingredient” – segment key
http://example.com/recipes/biryani
In Controller code:
we can get “biryani” from
params[:ingredient]
Passing additional parameters via
segment keys
●

Possible to insert additional hardcoded parameters
into route definitions
match 'products/special' => 'products#show',

true
●

Accessed in Controller code via
●

params[:special]

:special =>
Optional Segment Keys
●

Parentheses are used to define optional
segment keys
match ':controller(/:action(/:id(.:format)))
Segment Key Constraints
match 'products/:id' => 'products#show', :constraints => {:id

=> /d+/}

Shortcut:
match 'products/:id' => 'products#show', :id => /d+/
Segment Key Constraints
- More Powerful constraints checking
●

For more powerful constraints checking
–

We can pass a 'block' to “:constraints”
Redirect Routes
●

Possible to redirect using the redirect method
match “/google”, :to => redirect(“http://google.com/”)
Route Globbing
●

To grab more than 1 component
●

●

Use *

E.g.
/items/list/base/books/fiction/dickens
match 'items/list/*specs' => 'items#list'

●

In Controller code -

params[:specs]
2.) Generating URLs
Generating URLs
●

Original way (and simplest to understand) to
generate a URL ●

we have to supply values for the segment keys
using a Hash

Example :
link_to “Products”,
:controller => “products”,
:action => “show”,
:id => @product.id
Generating URLs (contd.)
●

More common way nowadays
●

using Named Routes
Named Routes
●

Created using :as parameter in a rule

●

Example:
match “item/:id” => “items#show”, :as => “item”
Named Routes – Behind the scenes
●

What actually happens when we name a route ?
2 New methods get defined
–

<name>_url , <name>_path

Example :
match “item/:id” => “items#show”, :as => “item ”
→ above line creates 2 new methods
●

●

item_path, item_url

These methods are used with link_to
●

to Generate Urls
Example
●

Scenario:
Suppose we have a Auction Site , and have Items
data
Goal - To display details of a particular Item

●

Starting Point
In routes.rb, we will already have
match “item/:id” => “items#show”
Example contd.
●

In the View (i.e .html.erb file) link_to “Auction of #{item.name}”,
:controller => “items”,
:action => “show”,
:id => item.id

How can the above code be improved by using
Named Routes ?
Example contd.
Let us make the following change in routes.rb
●

Original Route match “item/:id” => “items#show”

●

Append :as parameter to create Named Route match “item/:id” => “items#show”, :as => “item”
Example contd.
View code will change as follows:
●

Original “link_to” statement
link_to “Auction of #{item.name}”,
:controller => “items”,
:action => “show”,
:id => @item.id

●

Using named route
link_to “Auction of #{item.name}”,
item_path (:id => @item.id)
Shortcuts when using Named Routes
●

The Named route we created can further be
shortened :
FROM

link_to “Auction of #{item.name}”, item_path (:id =>
@item.id)
TO
Rails - “id” is default parameter, so we can drop “id”
wherever possible
link_to “Auction of #{item.name}”, item_path (@item.id)
link_to “Auction of #{item.name}”, item_path (@item)
More complicated Named Routes
●

Many Auctions and each Auction has Many
Items URL of Item details page /auction/5/item/1

●

Starting Point
We will probably already have
match “auction/:auction_id/item/:id” =>
“items#show”
More complicated Named Routes
(contd.)
●

Let us create a named route
by using :as
match “auction/:auction_id/item/:id” =>
“items#show” , :as => “item”
●

“link_to” statement changes
FROM:
link_to “Auction of #{item.name}”,
:controller => “items”,
:action => “show”,
:auction_id => @auction.id,
:id => @item.id
TO
link_to “Auction of #{item.name}”,
RESTful “resources” & Named Routes
●

resources :auctions
Above line in routes.rb creates 7 Routes out of
which 4 are Named Routes
RESTful “resources” & Named Routes
(contd.)
●

resources :auctions
resources :items
end
Scoping Routing Rules
“public” folder and Routing
Root route & “public” folder
●

In a newly generated Rails application
–

In routes.rb ●

–

root route is commented out

How is a page shown for the root URL ?
http://localhost:3000/
Root Route (contd.)
“public” folder
●

http://localhost:3000
=
http://localhost:3000/index.html

●

“public” folder in the root of our application
<=> root-level URL

●

That folder contains a “index.html”
“public” folder
●

Files in this folder will be scanned before
looking at of routing rules
●

Static content is usually put here

●

Cached content will be placed here

More Related Content

Similar to Rails training presentation routing

Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Henry S
 
Murach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routingMurach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routingMahmoudOHassouna
 
Angular 2 at solutions.hamburg
Angular 2 at solutions.hamburgAngular 2 at solutions.hamburg
Angular 2 at solutions.hamburgBaqend
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 AppFelix Gessert
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2Rory Gianni
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIEric Wise
 
Modern Perl Web Development with Dancer
Modern Perl Web Development with DancerModern Perl Web Development with Dancer
Modern Perl Web Development with DancerDave Cross
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
Routing in NEXTJS.pdf
Routing in NEXTJS.pdfRouting in NEXTJS.pdf
Routing in NEXTJS.pdfAnishaDahal5
 
Http programming in play
Http programming in playHttp programming in play
Http programming in playKnoldus Inc.
 
Ruby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapRuby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapMarcio Marinho
 
Building A Website - URLs and routing
Building A Website - URLs and routingBuilding A Website - URLs and routing
Building A Website - URLs and routingRahulRaj965986
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVCEmad Alashi
 

Similar to Rails training presentation routing (20)

Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
 
Angularjs
AngularjsAngularjs
Angularjs
 
Murach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routingMurach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routing
 
Angular 2 at solutions.hamburg
Angular 2 at solutions.hamburgAngular 2 at solutions.hamburg
Angular 2 at solutions.hamburg
 
Chapter5.pptx
Chapter5.pptxChapter5.pptx
Chapter5.pptx
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 App
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
Modern Perl Web Development with Dancer
Modern Perl Web Development with DancerModern Perl Web Development with Dancer
Modern Perl Web Development with Dancer
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Angular2 routing
Angular2 routingAngular2 routing
Angular2 routing
 
Rails::Engine
Rails::EngineRails::Engine
Rails::Engine
 
Routing in NEXTJS.pdf
Routing in NEXTJS.pdfRouting in NEXTJS.pdf
Routing in NEXTJS.pdf
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
GHC
GHCGHC
GHC
 
Ruby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapRuby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter Bootstrap
 
Building A Website - URLs and routing
Building A Website - URLs and routingBuilding A Website - URLs and routing
Building A Website - URLs and routing
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
Meteor iron:router
Meteor iron:routerMeteor iron:router
Meteor iron:router
 
Directives
DirectivesDirectives
Directives
 

Recently uploaded

The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...Operational Excellence Consulting
 
Unveiling the Soundscape Music for Psychedelic Experiences
Unveiling the Soundscape Music for Psychedelic ExperiencesUnveiling the Soundscape Music for Psychedelic Experiences
Unveiling the Soundscape Music for Psychedelic ExperiencesDoe Paoro
 
Planetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifePlanetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifeBhavana Pujan Kendra
 
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxGo for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxRakhi Bazaar
 
Entrepreneurship lessons in Philippines
Entrepreneurship lessons in  PhilippinesEntrepreneurship lessons in  Philippines
Entrepreneurship lessons in PhilippinesDavidSamuel525586
 
PSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationPSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationAnamaria Contreras
 
Appkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptxAppkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptxappkodes
 
NAB Show Exhibitor List 2024 - Exhibitors Data
NAB Show Exhibitor List 2024 - Exhibitors DataNAB Show Exhibitor List 2024 - Exhibitors Data
NAB Show Exhibitor List 2024 - Exhibitors DataExhibitors Data
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFChandresh Chudasama
 
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...ssuserf63bd7
 
Excvation Safety for safety officers reference
Excvation Safety for safety officers referenceExcvation Safety for safety officers reference
Excvation Safety for safety officers referencessuser2c065e
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMVoces Mineras
 
digital marketing , introduction of digital marketing
digital marketing , introduction of digital marketingdigital marketing , introduction of digital marketing
digital marketing , introduction of digital marketingrajputmeenakshi733
 
WSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfWSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfJamesConcepcion7
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03DallasHaselhorst
 
EUDR Info Meeting Ethiopian coffee exporters
EUDR Info Meeting Ethiopian coffee exportersEUDR Info Meeting Ethiopian coffee exporters
EUDR Info Meeting Ethiopian coffee exportersPeter Horsten
 
Pitch Deck Teardown: Xpanceo's $40M Seed deck
Pitch Deck Teardown: Xpanceo's $40M Seed deckPitch Deck Teardown: Xpanceo's $40M Seed deck
Pitch Deck Teardown: Xpanceo's $40M Seed deckHajeJanKamps
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
WSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdfWSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdfJamesConcepcion7
 
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdfChris Skinner
 

Recently uploaded (20)

The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
 
Unveiling the Soundscape Music for Psychedelic Experiences
Unveiling the Soundscape Music for Psychedelic ExperiencesUnveiling the Soundscape Music for Psychedelic Experiences
Unveiling the Soundscape Music for Psychedelic Experiences
 
Planetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifePlanetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in Life
 
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxGo for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
 
Entrepreneurship lessons in Philippines
Entrepreneurship lessons in  PhilippinesEntrepreneurship lessons in  Philippines
Entrepreneurship lessons in Philippines
 
PSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationPSCC - Capability Statement Presentation
PSCC - Capability Statement Presentation
 
Appkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptxAppkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptx
 
NAB Show Exhibitor List 2024 - Exhibitors Data
NAB Show Exhibitor List 2024 - Exhibitors DataNAB Show Exhibitor List 2024 - Exhibitors Data
NAB Show Exhibitor List 2024 - Exhibitors Data
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDF
 
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
 
Excvation Safety for safety officers reference
Excvation Safety for safety officers referenceExcvation Safety for safety officers reference
Excvation Safety for safety officers reference
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQM
 
digital marketing , introduction of digital marketing
digital marketing , introduction of digital marketingdigital marketing , introduction of digital marketing
digital marketing , introduction of digital marketing
 
WSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfWSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdf
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03
 
EUDR Info Meeting Ethiopian coffee exporters
EUDR Info Meeting Ethiopian coffee exportersEUDR Info Meeting Ethiopian coffee exporters
EUDR Info Meeting Ethiopian coffee exporters
 
Pitch Deck Teardown: Xpanceo's $40M Seed deck
Pitch Deck Teardown: Xpanceo's $40M Seed deckPitch Deck Teardown: Xpanceo's $40M Seed deck
Pitch Deck Teardown: Xpanceo's $40M Seed deck
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
WSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdfWSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdf
 
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
 

Rails training presentation routing

  • 2. 2 purposes of Routing 2 purposes of Routing 1) maps Requests to Controller Action methods 2) generation of URLs ● To be used as arguments to methods like link_to, redirect_to
  • 3. 1.) Mapping HTTP Requests to Controller-Actions
  • 4. Lifecycle of a HTTP Request
  • 5. routes.rb ● config/routes.rb ● specify 'Routing Rules' a.k.a 'Routes' here ● Order is important Rules are applied in the order in which they appear ● To list all routes: rake routes ● To filter routes :
  • 6. routes.rb (contd.) NOTE ● Whatever URLs have to work, have to be EXPLICITLY specified in routes.rb – Unless the .html file exists in “public” folder i.e. Even if we create Controller, ControllerAction, View → if there is no route for the URL in routes.rb, then that URL will NOT work
  • 7. routes.rb (contd.) ● A website may have many, many, URLs that need to work… so, how to specify all of them in routes.rb ? ● In routes.rb, when we create 'routing rules', we can specify patterns for permitted URLs (Next few slides talk about the Syntax used for specifying those 'routing rules')
  • 8. Legacy way that does Not work ● Legacy way of supplying controller and action parameters prior to Rails 3 does not work anymore # DOES NOT WORK match 'products/:id', :controller => “product”, :action => “show”
  • 9. Regular Syntax ● Regular syntax ● ● use :to match [URL Pattern], :to => Controller#Action E.g. match 'products/:id', :to => 'products#show'
  • 10. ShortCut – drop “:to” ● Full Syntax match 'products/:id' , :to => 'products#show' ● Shortcut match 'products/:id' => 'products#show' We can drop - , :to
  • 11. Another Shortcut Syntax – when path already has controller & action names ● Full Syntax match “/projects/status”, :to => “projects#status” ● Shortcut match “/projects/status” ● “projects” controller ● “status” action
  • 12. Constraining Request Methods and Shortcut ● To limit the HTTP method :via parameter match 'products/show', :to => 'products#show', :via ● Shortcut: get “/products/show” => :get
  • 13. Segment Keys ● match 'recipes/:ingredient' => “recipes#index” “:ingredient” – segment key http://example.com/recipes/biryani In Controller code: we can get “biryani” from params[:ingredient]
  • 14. Passing additional parameters via segment keys ● Possible to insert additional hardcoded parameters into route definitions match 'products/special' => 'products#show', true ● Accessed in Controller code via ● params[:special] :special =>
  • 15. Optional Segment Keys ● Parentheses are used to define optional segment keys match ':controller(/:action(/:id(.:format)))
  • 16. Segment Key Constraints match 'products/:id' => 'products#show', :constraints => {:id => /d+/} Shortcut: match 'products/:id' => 'products#show', :id => /d+/
  • 17. Segment Key Constraints - More Powerful constraints checking ● For more powerful constraints checking – We can pass a 'block' to “:constraints”
  • 18. Redirect Routes ● Possible to redirect using the redirect method match “/google”, :to => redirect(“http://google.com/”)
  • 19. Route Globbing ● To grab more than 1 component ● ● Use * E.g. /items/list/base/books/fiction/dickens match 'items/list/*specs' => 'items#list' ● In Controller code - params[:specs]
  • 21. Generating URLs ● Original way (and simplest to understand) to generate a URL ● we have to supply values for the segment keys using a Hash Example : link_to “Products”, :controller => “products”, :action => “show”, :id => @product.id
  • 22. Generating URLs (contd.) ● More common way nowadays ● using Named Routes
  • 23. Named Routes ● Created using :as parameter in a rule ● Example: match “item/:id” => “items#show”, :as => “item”
  • 24. Named Routes – Behind the scenes ● What actually happens when we name a route ? 2 New methods get defined – <name>_url , <name>_path Example : match “item/:id” => “items#show”, :as => “item ” → above line creates 2 new methods ● ● item_path, item_url These methods are used with link_to ● to Generate Urls
  • 25. Example ● Scenario: Suppose we have a Auction Site , and have Items data Goal - To display details of a particular Item ● Starting Point In routes.rb, we will already have match “item/:id” => “items#show”
  • 26. Example contd. ● In the View (i.e .html.erb file) link_to “Auction of #{item.name}”, :controller => “items”, :action => “show”, :id => item.id How can the above code be improved by using Named Routes ?
  • 27. Example contd. Let us make the following change in routes.rb ● Original Route match “item/:id” => “items#show” ● Append :as parameter to create Named Route match “item/:id” => “items#show”, :as => “item”
  • 28. Example contd. View code will change as follows: ● Original “link_to” statement link_to “Auction of #{item.name}”, :controller => “items”, :action => “show”, :id => @item.id ● Using named route link_to “Auction of #{item.name}”, item_path (:id => @item.id)
  • 29. Shortcuts when using Named Routes ● The Named route we created can further be shortened : FROM link_to “Auction of #{item.name}”, item_path (:id => @item.id) TO Rails - “id” is default parameter, so we can drop “id” wherever possible link_to “Auction of #{item.name}”, item_path (@item.id) link_to “Auction of #{item.name}”, item_path (@item)
  • 30. More complicated Named Routes ● Many Auctions and each Auction has Many Items URL of Item details page /auction/5/item/1 ● Starting Point We will probably already have match “auction/:auction_id/item/:id” => “items#show”
  • 31. More complicated Named Routes (contd.) ● Let us create a named route by using :as match “auction/:auction_id/item/:id” => “items#show” , :as => “item”
  • 32. ● “link_to” statement changes FROM: link_to “Auction of #{item.name}”, :controller => “items”, :action => “show”, :auction_id => @auction.id, :id => @item.id TO link_to “Auction of #{item.name}”,
  • 33. RESTful “resources” & Named Routes ● resources :auctions Above line in routes.rb creates 7 Routes out of which 4 are Named Routes
  • 34. RESTful “resources” & Named Routes (contd.) ● resources :auctions resources :items end
  • 37. Root route & “public” folder ● In a newly generated Rails application – In routes.rb ● – root route is commented out How is a page shown for the root URL ? http://localhost:3000/
  • 38. Root Route (contd.) “public” folder ● http://localhost:3000 = http://localhost:3000/index.html ● “public” folder in the root of our application <=> root-level URL ● That folder contains a “index.html”
  • 39. “public” folder ● Files in this folder will be scanned before looking at of routing rules ● Static content is usually put here ● Cached content will be placed here