Routes & REST & URL-helpers & validations & filters

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

MWD1001 Website Production Using JavaScript with Forms.
Presenter: James Huang Date: Sept. 29,  HTTP and WWW  Bottle Web Framework  Request Routing  Sending Static Files  Handling HTML  HTTP Errors.
CIS 4004: Web Based Information Technology Spring 2013
The Librarian Web Page Carol Wolf CS396X. Create new controller  To create a new controller that can manage more than just books, type ruby script/generate.
Ruby on Rails Model of MVC. Model-View-Controller Paradigm A way of organizing a software system Benefits: Isolation of business logic from the user interface.
Feature requests for Case Manager By Spar Nord Bank A/S IBM Insight 2014 Spar Nord Bank A/S1.
Objectives Using functions to organize PHP code
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
CS 290C: Formal Models for Web Software Lecture 10: Language Based Modeling and Analysis of Navigation Errors Instructor: Tevfik Bultan.
15-Jun-15 Rails and Ajax. HTML Forms The... tag encloses form elements (and usually includes other HTML as well) The arguments to form tell what to do.
1 Cleaning up the Internet Using AJAX, SOAP and Comet CS526 Mike Gerschefske Justin Gray James Yoo 02 May 2006.
CSE 115 Week 4 February 4 - 8, Monday Announcements Software installation fest Tuesday & Wednesday 4-7 in Baldy 21. Software installation fest Tuesday.
5/3/2006 Mike/Justin/JYoo AJAX/SOAP/Comet 1 Cleaning up the Internet Using AJAX, SOAP and Comet CS526 Mike Gerschefske Justin Gray James Yoo 02 May 2006.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
RUBY ON RAILS CS 186 – Arsalan Tavakoli 3/18/2008 Slides adapted from CS 198 slides with the gracious permission of Armando Fox and Will Sobel.
1 Spidering the Web in Python CSC 161: The Art of Programming Prof. Henry Kautz 11/23/2009.
J2EE Web Fundamentals Lesson 1 Introduction and Overview
NextGen Technology upgrade – Synerizip - Sandeep Kamble.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
JavaScript Form Validation
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
UC Berkeley Hello Rails. Review: MVC Goal: separate organization of data (model) from UI & presentation (view) by introducing controller –mediates user.
JavaScript & jQuery the missing manual Chapter 11
REST.  REST is an acronym standing for Representational State Transfer  A software architecture style for building scalable web services  Typically,
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
1 Dr Alexiei Dingli Web Science Stream Helpers, Forms and Layouts.
MVC & ActiveRecord by Christian Mohr & Mohamed Souiai.
1 Dr Alexiei Dingli Web Science Stream Advanced ROR.
Introduction to ASP.NET MVC Information for this presentation was taken from Pluralsight Building Applications with ASP.NET MVC 4.
Ruby on Rails Your first app. Rails files app/ Contains the controllers, models, views and assets for your application. You’ll focus on this folder for.
Lecture 11 Rails Topics SaaSSaaS Readings: SaaS book Ch February CSCE 740 Software Engineering.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Associations INFO 2310: Topics in Web Design and Programming.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Photo Gallery INFO 2310: Topics in Web Design and Programming.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Review for exam 1 Midterm Closed Book. Review for Exam 1 Blackboard topic Review for exam 1 Sample Question Multiple Choice True / False Matching type.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
XP New Perspectives on XML, 2 nd Edition Tutorial 8 1 TUTORIAL 8 CREATING ELEMENT GROUPS.
Chapter 15 © 2013 by Pearson Overview of Rails - Rails is a development framework for Web-based applications - Based on MVC architecture for applications.
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
Create, Update and Delete Carol Wolf Computer Science.
Student Pages
ICM – API Server & Forms Gary Ratcliffe.
CS 4720 Model-View-Controller CS 4720 – Web & Mobile Systems.
Date : 3/04/2010 Web Technology Solutions Class: PHP Web Application Frameworks.
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Ruby on Rails Controller of MVC. Routes How we map URIs like /tweets/1 to calling the show method of the Controller.
Rails and routing INFO 2310: Topics in Web Design and Programming.
AJAX Use Cases for WSRP Subbu Allamaraju BEA Systems Inc WSRP F2F Meeting, May 2006.
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
Chapter 2 - OOP Maciej Mensfeld Presented by: Maciej Mensfeld More about OOP dev.mensfeld.pl github.com/mensfeld.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
CS 160 and CMPE/SE 131 Software Engineering February 11 Class Meeting Department of Computer Science Department of Computer Engineering San José State.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
Ruby on Rails. Web Framework for Ruby Designed to make it easier to develop, deploy, and maintain web applications Design with Model-View-Controller –almost.
This was written with the assumption that workbooks would be added. Even if these are not introduced until later, the same basic ideas apply Hopefully.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
HTML III (Forms) Robin Burke ECT 270. Outline Where we are in this class Web applications HTML Forms Break Forms lab.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
Presented by Alexey Vedishchev Developing Web-applications with Grails framework American University of Nigeria, 2016 Part VI: Mapping URLs.
Data and tools on the Web have been exposed in a RESTful manner. Taverna provides a custom processor for accessing such services.
Web Technology Solutions
Data Virtualization Tutorial… CORS and CIS
Lecture 5: Functions and Parameters
Presentation transcript:

Routes & REST & URL-helpers & validations & filters CS 98-10/CS 198-10 Web 2.0 Programming Using Ruby on Rails Armando Fox

Administrivia Office hours switched (again...sorry) Tuesdays 1:30-2:30 in 413 Soda Monday: Project brainstorming Weds: Project groups informally chosen-up By following Monday: start planning your app (user stories, testing, deployment....) Technical material: Routes & REST (today), more on controllers & views

Outline... Routing basics: how do.... REST and RESTful routes URLs get mapped to a controller and action? link_to, redirect_to etc. generate their URLs? REST and RESTful routes what is RESTful resource access? how Rails 2.0 routing supports REST URL helpers generating URL’s (for your pages) that will map to specific controller actions...RESTfully Further reading “Rails Way” book has good content on this “Agile” book has routes, but not 2.0 routes and REST Model validations, callbacks, controller filters

$APP_ROOT/config/routes.rb Ruby code (that makes use of high-level methods!) to declare “rules” for mapping incoming URLs to controllers/actions actually each rule has 2 purposes: map incoming URL to ctrler/action/params generate URL to match ctrler/action/params e.g. when using link_to, redirect_to, etc. What’s in a rule? A URL template Keywords stating what to do

Simple example In routes.rb: In one of your views: map.connect 'professors/:dept', :controller => 'professors', :action => 'list' In one of your views: <%= link_to "List professors in EECS", :controller => 'professors', :action => 'list', :dept => 'eecs', :hired_since => 2005 %> matching is determined by keywords link_to uses underlying function url_for, which consults routing rules to build the URL: http://www.yourapp.com/professors/eecs?hired_since=2005

Simple example cont. Now if someone visits this URL: In routes.rb: map.connect 'professors/:dept', :controller => 'professors', :action => 'list' Now if someone visits this URL: http://www.yourapp.com/professors/eecs Matching is determined by position How about: http://www.yourapp.com/professors/eecs?glub=1&hired_since=2006 http://www.yourapp.com/professors

Default routes URL is compared to routing rules, one at a time, until match found then “wildcard” pieces of URL get put into params[] If no match, default route (last one in routes.rb) is used typically something like: map.connect ':controller/:action/:id' e.g., catches things like professors/edit/35 Warning! Can lead to dangerous behaviors Use the root route to map the “empty” URL (e.g. http://www.myapp.com): map.root :controller=>'main', :action=>'index'

More on Routes Ordering of routes matters; more specific ones should come earlier so they’ll match first map.connect 'users/:action/:id' map.connect ':controller/:action/:id' Many, many apps will never need to use more than the “conventional” predefined routes If you want to, you should definitely read more about routes offline

REST is CRUD REST Idea: each HTTP interaction should specify, on its own, a CRUD operation and which object to do it on. GET used for read operations; POST for writes (create, update, delete) Also guards against spidering/bots! Rails 2.0: routes, scaffolds and URL helpers are now all RESTful by default result: syntax of link_to, etc. has changed Get them by saying map.resources :model

REST and URI’s HTTP method Old style URL New (RESTful) style URL Action & named route method to pass to url_for HTTP method Old style URL New (RESTful) style URL show: student_url(@s) GET /:ctrl/show/:id /:ctrl/:id index (list): students_url /:ctrl/list (or /:ctrl/index) /:ctrl new: new_student_url /:ctrl/new create: students_url POST /:ctrl/create (why no ID?) destroy: student_url(@s) DELETE /:ctrl/destroy/:id /:ctrl (but see Hack!) edit: edit_student_url(@s) /:ctrl/edit/:id /:ctrl/:id/edit update: student_url(@s) PUT /:ctrl/update/:id

The DELETE & PUT hack REST says: use HTTP method DELETE to request deletion; PUT to request Update But: Web browsers only have GET and POST “Solution”: use POST, but include extra field _method with value DELETE or PUT routing takes care of parsing this out to disambiguate dispatching done with JavaScript in link_to (but you shouldn’t be using link_to for this...why?) or use button_to which creates a self-contained form for a single button

How url_for has changed Excerpted from REST Cheat Sheet which I’m trying to get a site license for (Peepcode) Note use of either _path or _url suffix

That whole thing with respond_to do |format| Let’s make it easier to read by: put the if...else outside the do block change variable name format to wants

Easier-to-read version respond_to accepts a block, and yields to it passing the wants object wants’s instance methods named for possible MIME output types (HTML, XML, etc.) Each of those methods takes a block that specifies what to do for each format Based on parsing HTTP headers from request Many, many MIME types predefined (add more in environment.rb) A useful one when we do AJAX: js (runs .rjs template if available)

What about redirect_to? RESTful routing strikes again! url_for and friends now assume RESTful routes by default Hint: consider url_for(@student) Or redirect_to(edit_student_path(@student)), etc.

Nested routes Consider a Course that belongs_to :professor (and as well, Professor has_many :courses) In particular, it makes no sense to have a course without a professor in our app, I mean When invoking CRUD methods on a course, we’d like to be able to specify which professor it belongs_to

Enter nested RESTful routes map.resources :professors do |p| p.resources :courses end —or— map.resources :professors, :has_many=>:courses Now you can say course_path(:professor_id=>3, :id=>20) and get a RESTful URI for course ID 20 that belongs to professor ID 3. Note! The route builder doesn’t check if the belongs_to relationship keys match what’s in the database!

In Courses controller... Need to set up the @professor that owns the course in each of the methods Otherwise the URL-builder methods won’t know what the parent object ID is Ugly (we’ll learn a better way with filters): def index @professor = Professor.find(params[:professor_id]) @courses = @professor.courses.find(:all) ...etc... end def update ...if update of Course fails... redirect_to([@professor,@course])

What about views for nested models? # example: views/courses/edit.html.erb <% form_for([@professor,@course]) do |f| %> <%= f.text :description %> <%= f.text :ccn %> <%= f.submit "Save Changes" %> <% end %> <%= link_to "Show", [@professor,@course]) %> or... link_to "Show", course_path(@course) if makes sense <%= link_to "Back", professor_courses_path(@professor) %>

In your index (list) view... <% @courses.each do |c| %> <tr> <td> c.name </td> <td><%= link_to "Edit",edit_course_path([@professor,c]) %> </td> <td><%= link_to "Show",course_path([@professor,c])%></td> <td> <%= button_to "Destroy", course_path([@professor,c]),:method=>:delete %></td> </tr> <% end %> Similarly for other views

Worth understanding... Routing and REST caused lots of changes in 2.0, but ultimately they will make life better Best tutorial we’ve found (thx Arthur!): http://www.akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial (Linked from course home page)

Controller predicates: verify A declarative way to assert various preconditions on calling controller methods You can check selectively (:only, :except) for: HTTP request type (GET, POST, Ajax XHR) Presence of a key in the flash or the session Presence of a key in params[] And if the check fails, you can... redirect_to somewhere else add_to_flash a helpful message Example: verify :method => :post, :only => 'dangerous_action', :redirect_to => {:action => 'index'}, :add_to_flash => "Dangerous action requires Post"

More General Filters Code blocks that can go before, after or around controller actions; return Boolean before_filter :filter_method_name before_filter { |controller| ... } before_filter ClassName options include :only,:except, etc. multiple filters allowed; calls provided to prepend or append to filter chain subclasses inherit filters but can use skip_filter methods to selectively disable them If any before-filter returns false, chain halted & controller action method won’t be invoked so filter should redirect_to, render, or otherwise deal with the request Simple useful example: a before-filter for nested routes! before_filter :load_professor def load_professor @professor = Professor.find(params[:professor_id]) end

A General Pattern: “Do It Declaratively” More and more ways to specify what should be done rather than how to do it Should always be asking yourself this question Especially when you find yourself (re)writing common code in multiple places!