To Ponder (recall…)
Transcript of To Ponder (recall…)
Computer Science and Engineering n The Ohio State University
To Ponder (recall…)
o GET, HEADn Request: should be safe (no side effects)n Request has header only (no body)
o PUTn Update (or create): should be idempotent
o DELETEn Delete: should be idempotent
o POSTn Create (or update): changes server staten Beware re-sending!
o HTTP does not enforce these semantics
Computer Science and Engineering n College of Engineering n The Ohio State University
Rails:Routes
Lecture 21
Computer Science and Engineering n The Ohio State University
Recall: Rails Architecture
Computer Science and Engineering n The Ohio State University
Configuration
o Need to map an HTTP request (verb, URL, parameters) to an application action (a method in a Ruby class)n Framework invokes the method, passing in
parameters from HTTP request as argumentsn Results in an HTTP response, typically with an
HTML payload, sent back to client's browsero These mappings are called routeso Defined in config/routes.rb
n Ruby code, but highly stylized (another DSL)n Checked top to bottom for first match
Computer Science and Engineering n The Ohio State University
Basic Routeo Pattern string + application action
n In config/routes.rbn Pattern string usually contains segments
o Example routeget 'status/go/:system/memory/:seg',
to: 'reporter#show'o Matches any HTTP request like
GET /status/go/lander/memory/0?page=3o Result:
n Instantiates ReporterControllern Invokes show method on that new instancen Provides an object called params (like a hash)params = { system: 'lander',
seg: '0',page: '3' }
Computer Science and Engineering n The Ohio State University
Default Valueso Special segments
n :controller - the controller class to usen :action - the method to invoke in that controller
o Example routeget ':controller/go/:action/:system'
o Matches any HTTP request likeGET /reporter/go/show/lander?page=3
o Result:n Instantiates ReporterControllern Invokes show method on that new instancen Provides an object called paramsparams = { system: 'lander',
page: '3',# also :controller and :action }
Computer Science and Engineering n The Ohio State University
Customizing Routes
o Recognize different HTTP verb(s)n get, put, post, deleten Alternative: match via: [:get, :post]
o Optional segments with ( )get ':controller(/:action(/:id))'
o Default values for paramsget 'photos/:id', to: 'photos#show',
defaults: { format: 'jpg' }
Computer Science and Engineering n The Ohio State University
REST
o REpresentational State Transfern An architectural style for web applicationsn Maps database operations to HTTP requests
o Small set of database operations (CRUD)n Create, Read, Update, Delete
o Small set of HTTP verbs, with fixed semantics (e.g., idempotence)n GET, POST, PUT, DELETE
o The protocol is statelesso Resource: bundle of (server-side) state
n Each resource is identified by a URL
Computer Science and Engineering n The Ohio State University
Resources
o A resource could be an individual membern Example: a single studentn Corresponds to a row in a table
o A resource could be a collection of itemsn Example: a set of studentsn Corresponds to a table
o In REST, resources have URLsn Each member element has its own URL
http://quickrosters.com/students/42
n Each collection has its own URLhttp://quickrosters.com/students
Computer Science and Engineering n The Ohio State University
Read Collection: GET
Request
GET /students HTTP/1.1Host: quickrosters.com
Computer Science and Engineering n The Ohio State University
Read Collection: GET
Request
GET /students HTTP/1.1Host: quickrosters.com
Computer Science and Engineering n The Ohio State University
Read Collection: GET
Computer Science and Engineering n The Ohio State University
HTML Source (GET Collection)…<h1>Students</h1><table><tr><th>Fname</th><th>Lname</th><th>Buckid</th><th colspan="3"></th>
</tr>…<tr><td>Primo</td><td>Carnera</td><td>334432</td><td><a href="/students/3">Show</a></td><td><a href="/students/3/edit">Edit</a></td><td><a href="/students/3" data-confirm="Are you sure?"
data-method="delete" rel="nofollow">Destroy</a></td></tr>
…</table><a href="/students/new">New Student</a>
Computer Science and Engineering n The Ohio State University
Read Member: GET
Request
GET /students/3
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes (R)
Collection/students
Member/students/42
GET List all members Show info about a member
PUT
POST
DELETE
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes (CR)
Collection/students
Member/students/42
GET List all members Show info about a member
PUT
POST
DELETE
o How to map “create member” action?n Member doesn’t exist è target is collectionn Creation is not idempotent è verb is…
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes (CR)
Collection/students
Member/students/42
GET List all members Show info about a member
PUT
POST Create a new member
DELETE
o How to map “create member” action?n Member doesn’t exist è target is collectionn Creation is not idempotent è verb is…
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes (CRU)
Collection/students
Member/students/42
GET List all members Show info about a member
PUT
POST Create a new member
DELETE
o How to map “update member” action?n Target is a membern Update overwrites, so it is idempotent…
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes (CRU)
Collection/students
Member/students/42
GET List all members Show info about a member
PUT Update member
POST Create a new member
DELETE
o How to map “update member” action?n Target is a membern Update overwrites, so it is idempotent…
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes (CRUD)
Collection/students
Member/students/42
GET List all members Show info about a member
PUT Update member
POST Create a new member
DELETE Delete this member
o Delete action destroys a member
Computer Science and Engineering n The Ohio State University
Minimal Set of Routes
Collection/students
Member/students/42
GET List all members Show info about a member
PUT Update member
POST Create a new member
DELETE Delete this member
o Implicationsn You can't delete a collectionn No idempotent operations on collection
Computer Science and Engineering n The Ohio State University
Typical Workflow: Delete
o How does one destroy a member?n Need to issue an HTTP request:DELETE /students/4
o Protocol:n GET the collection to see the listn Click a button next to one item in the list
to issue a DELETE for that membero Alternative:
n GET the member to see the detailsn Click a button to issue a DELETE for that
member
Computer Science and Engineering n The Ohio State University
GET List, DELETE Member
GET /students
DELETE /students/4
Computer Science and Engineering n The Ohio State University
Typical Workflow: Create
o How does one issue a POST on collection?n GET a (blank) formn Fill in fields of formn Click a button to submit, resulting in the
POSTo That first GET is a new route
n GET on the collectionn But instead of a list of members, the
result is a form to be filled in and submitted
Computer Science and Engineering n The Ohio State University
GET Blank Form, POST the Form
GET "a blank form"
POST /studentslname: …etc
Computer Science and Engineering n The Ohio State University
Standard Set of Routes
Collection/students
Member/students/42
GET 1. List all members2. Form for entering a new member's data
1. Show info about a member
PUT Update member
POST Create a new member
DELETE Delete this member
Computer Science and Engineering n The Ohio State University
HTML Source…<h1>Students</h1><table><tr><th>Fname</th><th>Lname</th><th>Buckid</th><th colspan="3"></th>
</tr>…<tr><td>Primo</td><td>Carnera</td><td>334432</td><td><a href="/students/3">Show</a></td><td><a href="/students/3/edit">Edit</a></td><td><a href="/students/3" data-confirm="Are you sure?"
data-method="delete" rel="nofollow">Destroy</a></td></tr>
…</table><a href="/students/new">New Student</a>
Computer Science and Engineering n The Ohio State University
Typical Workflow: Update
o How does one issue a PUT on a member?n GET a (populated) formn Edit the fields of the formn Click a button to send, resulting in the
PUTo That first GET is a new route
n GET on a membern But instead of a display of information
about that member, the result is a populated form to modify and submit
Computer Science and Engineering n The Ohio State University
GET Filled Form, PUT the Form
GET "a populated form"
PUT /students/4lname: …etc
Computer Science and Engineering n The Ohio State University
Standard Set of Routes
Collection/students
Member/students/42
GET 1. List all members2. Form for entering a new member's data
1. Show info about a member2. Form for editing an existing
member's dataPUT Update member
POST Create a new member
DELETE Delete this member
Computer Science and Engineering n The Ohio State University
HTML Source…<h1>Students</h1><table><tr><th>Fname</th><th>Lname</th><th>Buckid</th><th colspan="3"></th>
</tr>…<tr><td>Primo</td><td>Carnera</td><td>334432</td><td><a href="/students/3">Show</a></td><td><a href="/students/3/edit">Edit</a></td><td><a href="/students/3" data-confirm="Are you sure?"
data-method="delete" rel="nofollow">Destroy</a></td></tr>
…</table><a href="/students/new">New Student</a>
Computer Science and Engineering n The Ohio State University
Rails Resource-Based Routeso For a resource like :students, the action pack
includesn 1 controller (StudentsController)n 7 routes (each with a method in controller)n 4 Views (list of students, show 1 student, new, edit)
HTTPVerb
URL Resource Method Response(View)
GET /students Collection index list allPOST /students Collection create show oneGET /students/new Collection new blank formGET /students/3 Member show show oneGET /students/3/edit Member edit filled formPUT /students/3 Member update show oneDELETE /students/3 Member destroy list all
Computer Science and Engineering n The Ohio State University
Defining Resource-Based Routes
o In RosterTool app’s config/routes.rbRails.application.routes.draw do
resources :studentsresources :faculty
end
Computer Science and Engineering n The Ohio State University
Customizing Routeso To change which 7 routes are created
resources :students, except:[:update, :destroy]
resources :grades, only: [:index, :show]o To specify a particular controller
resources :students, controller: 'ugrads'o To rename certain actions
resources :students, path_names:{ create: 'enroll' }
o To add more routes to standard setn Add GET /students/:id/avatar (i.e. on member)n Add GET /students/search (i.e. on collection)resources :students doget 'avatar', on: :memberget 'search', on: :collection
end
Computer Science and Engineering n The Ohio State University
Segment Keyso URL request has arguments for controller
n Example: products/42n Pattern string: 'products/:id'
o Segment key gets value when route matches
o Controller gets a hash (called params) of segment keys and their valuesn Example: params[:id] is '42'
o Common case: Look up an item by iddef set_product@product = Product.find(params[:id])
end
Computer Science and Engineering n The Ohio State University
Recognition vs Generationo Dual problems
n Recognize a URL (request for an action)n Generate a URL (a hyperlink or redirect)
o Routes used for both!o For generation, route must be named
get 'status/:seg', to: 'reporter#show',as: :info
o Results in two helpers (_path, _url)info_path(4)#=> "/status/4"info_url(4) #=> "http://faces.com/status/4"
o Used with link_to to generate hyperlinkslink_to 'S', info_path(4), class: 'btn'#=> "<a class='btn' href='/status/4'>S</a>"
Computer Science and Engineering n The Ohio State University
Helper Methods for Resourceso Resource-based routes have names
photos_path #=> /photosphotos_url #=> http://faces.com/photosnew_photo_path #=> /photos/newphoto_path(:id) #=> /photos/4edit_photo_path(:id) #=> /photos/4/edit
Name HTTP URL Resource Method
photos GET /photos Collection index
POST /photos Collection create
new_photo GET /photos/new Collection new
photo GET /photos/3 Member show
edit_photo GET /photos/3/edit Member edit
PUT /photos/3 Member update
DELETE /photos/3 Member destroy
Computer Science and Engineering n The Ohio State University
Debugging Routes and Helperso To see the full list of routes
$ rails routesPrefix Verb URI Contr#Actioninfo GET /status/:seg reporter#show
photos GET /photos photos#indexPOST /photos photos#create
photo GET /photo/:id photos#showedit_photo GET /photos/:id/edit ……etc…
o To see/use helpers in the console$ rails console> app.edit_photo_path(42)=> "/photos/42/edit"> helper.link_to "Click here",
app.edit_photo_path(42)=> "<a href="/photos/42/edit">Click here</a>
Computer Science and Engineering n The Ohio State University
Root Route
o With no matching route, GET for http://example.com gets index.html from application's public directory
o To customize landing page, 2 choices:n Create public/index.htmln Add root route to config/routes.rb,
pointing to a controller#action (better)root to: "welcome#index"
Computer Science and Engineering n The Ohio State University
Singleton Resourceso Declared with singular syntax
resource :systemo You get only 1 resource, not 2
n Controller still plural (e.g., SystemsController)n URLs are singular (e.g., /system/edit
o Only 6 standard routesn No index collection action to list membersn POST /system -> createn GET /system/new -> newn GET /system/edit -> editn GET /system -> shown PUT /system -> updaten DELETE /system -> destroy
Computer Science and Engineering n The Ohio State University
Summary
o REST and CRUDn Create, read, update, destroyn Map data to resourcesn Map actions to HTTP requests (verb +
URL)o Routes
n Connect HTTP request to specific method in a controller class
n Defined in config/routes.rbn Resource based, or match-basedn Dual problem: recognition and generation