Rails and routing INFO 2310: Topics in Web Design and Programming.

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

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.
JavaScript and Ajax INFO 2310: Topics in Web Design and Programming.
Browsers and Servers CGI Processing Model ( Common Gateway Interface ) © Norman White, 2013.
World Wide Web1 Applications World Wide Web. 2 Introduction What is hypertext model? Use of hypertext in World Wide Web (WWW) – HTML. WWW client-server.
Python and Web Programming
Creating a wiki blog. Run apps that come with instant rails distribution select I /rails applications/open ruby console window Cd to cookbook or typo.
CGI Programming: Part 1. What is CGI? CGI = Common Gateway Interface Provides a standardized way for web browsers to: –Call programs on a server. –Pass.
Intro to Rails INFO 2310: Topics in Web Design and Programming.
UNIT-V The MVC architecture and Struts Framework.
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. What is Ruby on Rails? Ruby on Rails is an open source full-stack web framework. It is an alternative to PHP/MySQL. It can render templates,
J2EE Web Fundamentals Lesson 1 Introduction and Overview
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
1 Introduction to PHP. 2 What is this “PHP” thing? Official description: “PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source.
Web forms in PHP Forms Recap  Way of allowing user interaction  Allows users to input data that can then be processed by a program / stored in a back-end.
JavaScript Form Validation
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
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.
Lab Assignment 7 | Web Forms and Manipulating Strings Interactive Features Added In this assignment you will continue the design and implementation of.
Server-side Scripting Powering the webs favourite services.
ASP.NET and Model View Control Jesper Tørresø ITNET2 F08.
Ajax and Ruby on Rails Session 9 INFM 603.
1 Dr Alexiei Dingli Web Science Stream Helpers, Forms and Layouts.
FUNCTIONS AND STORED PROCEDURES & FUNCTIONS AND PROTECTING A DB AND PHP (Chapters 9, 15, 18)
CSCI 6962: Server-side Design and Programming Introduction to Java Server Faces.
MVC & ActiveRecord by Christian Mohr & Mohamed Souiai.
1 Dr Alexiei Dingli Web Science Stream Advanced ROR.
PHP meets MySQL.
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.
Murach’s ASP.NET 4.0/VB, C1© 2006, Mike Murach & Associates, Inc.Slide 1.
Lecture 11 Rails Topics SaaSSaaS Readings: SaaS book Ch February CSCE 740 Software Engineering.
Ruby on Rails CSE 190M, Spring 2009 Week 6. Overview How to use a database Demo creating a blog application on Rails Explain how the application works.
 Whether using paper forms or forms on the web, forms are used for gathering information. User enter information into designated areas, or fields. Forms.
Associations INFO 2310: Topics in Web Design and Programming.
1 Dr Alexiei Dingli Web Science Stream A ROR Blog.
Photo Gallery INFO 2310: Topics in Web Design and Programming.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Routes & REST & URL-helpers & validations & filters
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
Chapter 15 © 2013 by Pearson Overview of Rails - Rails is a development framework for Web-based applications - Based on MVC architecture for applications.
1 Web Servers (Chapter 21 – Pages( ) Outline 21.1 Introduction 21.2 HTTP Request Types 21.3 System Architecture.
1 WWW. 2 World Wide Web Major application protocol used on the Internet Simple interface Two concepts –Point –Click.
Create, Update and Delete Carol Wolf Computer Science.
IS-907 Java EE World Wide Web - Overview. World Wide Web - History Tim Berners-Lee, CERN, 1990 Enable researchers to share information: Remote Access.
Web Design and Development. World Wide Web  World Wide Web (WWW or W3), collection of globally distributed text and multimedia documents and files 
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
CS 4720 Model-View-Controller CS 4720 – Web & Mobile Systems.
RESTful Web Services What is RESTful?
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
HTML Forms.
Ruby on Rails Controller of MVC. Routes How we map URIs like /tweets/1 to calling the show method of the Controller.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 2: Introduction to IS2803 Rob Gleasure
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
Introduction  “M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner.
CS 160 and CMPE/SE 131 Software Engineering February 11 Class Meeting Department of Computer Science Department of Computer Engineering San José State.
: Information Retrieval อาจารย์ ธีภากรณ์ นฤมาณนลิณี
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.
INTERNET APPLICATIONS CPIT405 Forms, Internal links, meta tags, search engine friendly websites.
Web Services Essentials. What is a web service? web service: software functionality that can be invoked through the internet using common protocols like.
REST API Design. Application API API = Application Programming Interface APIs expose functionality of an application or service that exists independently.
Presented by Alexey Vedishchev Developing Web-applications with Grails framework American University of Nigeria, 2016 Part VI: Mapping URLs.
National College of Science & Information Technology.
Play Framework: Introduction
MVC Framework, in general.
Controllers.
Developing a Model-View-Controller Component for Joomla
MVC Controllers.
Presentation transcript:

Rails and routing INFO 2310: Topics in Web Design and Programming

Today’s topics Model validation –How can we make sure people enter stuff we want? More about views and controllers –How does Rails decide what pages to show? –RESTful design Embedded Ruby (erb) –How can we use Ruby in our HTML?

Model validation

Remember the CD catalog from INFO 230? You can’t trust user input. So how do we deal with that in Rails?

Model validation It turns out to be particularly simple in Rails. Open up your Post model file (blog/app/models/post.rb). Add the line: validates_presence_of :title, :body to the Post model.

Now try it… Fire up the webserver ( ruby script/server from within your blog directory) and open up a browser (to ). Try entering/editing a post to have a blank title and/or body.

We can be slightly more sophisticated. Add another line to the Post model: validates_format_of :title, :with => /^[\w\d]+$/ Now try to see what happens…

Lots of possibilities… validates_uniqueness_of validates_numericality_of validate_on_create :methodname validate_on_update :methodname …

Errors? How are the errors getting displayed? Each ActiveRecord object has a list of errors If you look at blog/app/views/post/new.erb.html blog/app/views/post/edit.erb.html you’ll see a method that prints out the errors in this list:

More about views and controllers

From last time: MVC Recall from last time: Rails uses the MVC (model-view-controller) pattern of software architecture Model: Objects holding data + methods for operating on them. Controllers: Takes requests from user interface and decide which views to render. Views: The HTML + Ruby that displays data from the model, gets input from the user.

From last time: Models In working on our blog, we created a model ‘Posts’ with titles and bodies. We saw how we could manipulate data in the model.

This time: Views and controllers How does Rails take a URL and decide what to show you?

Routes.rb Everything starts in the routes.rb file. Open up blog/config/routes.rb.

Routes.rb ActionController::Routing::Routes.draw do |map| map.resources :posts map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format’ end

Figuring a route Each map.something command designed to take a URL, parse it, and direct it to the appropriate controller and method (action). Route is decided on by first matching URL in routes.rb. E.g. For our current mapping, /users/show/1 would match map.connect ‘:controller/:action/:id’ with params = { :controller => “users”, :action => “show”, :id => 1 } Would call on users_controller.rb and look for ‘show’ method. (if we had a users_controller). ‘show’ can access params[:id].

Let’s add some routes First, let’s add a route for the root, so we don’t get the default Rails screen. Add map.root :controller => ‘posts’, :action => ‘index’ to routes.rb, just before the map.connect :controller/:action/:index line. Also delete blog/public/index.html (or rename it). Try it!

Another route Let’s allow us to look up blog posts by date. As the first routing line in routes.rb (after ActionController…), add map.connect ‘posts/bydate/:year/:month/:day’, :controller => “posts”, :action => “show_date”, :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/ }, :month => nil, :day => nil (Note: for reasons we’ll discuss in a minute, this isn’t something we would really want to do given how posts current works).

Adding an action to a controller Now open up blog/app/controller/posts_controller and add the following method at the bottom (just before the ‘end’). def = {|x| x.created_at.year == {|x| x.created_at.month == params[:month].to_i} if {|x| x.created_at.day == params[:day].to_i} if params[:day] render(:action => :index) end

Try it! Try entering corresponding URLs into the browser

What is happening?

Views Each controller/action may have an associated layout/view. The ‘posts’ controller has an associated layout in app/layouts/posts.html.erb. The views associated with the actions of the ‘posts’ controllers are in app/views/post/… (ones for ‘index’, ‘edit’, ‘new’, and ‘show’).

Views When an action is called, the corresponding view is rendered (unless another render or a ‘redirect’ is called). The view is output within a layout; posts.html.erb in this case. If the corresponding layout does not exist, application.html.erb is used instead (useful if you want one layout for many controllers).

In our case… ‘show_date’ asks to render ‘index’. So app/views/posts/index.html.erb is rendered in the context of the layout app/layouts/posts.html.erb (with variable set as given in ‘show_date’).

Posts layout !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " My Blog

Useful tricks Since layouts are evaluated after the view, they can use variables set in the view. Try this: in app/views/posts/show.html.erb add the line somewhere.

Then in app/layouts/post.html.erb, change the tag to My Blog Try it!

REST

But in fact, the only route related to posts in routes.rb was map.resources :posts How does this manage to do everything that it does?

REST REST = Representational State Transfer Basic ideas: All interactions between client and server handled by a small number of ‘verbs’ applied to a larger number of well-defined ‘nouns’ or ‘resources’. ‘Resources’ can have multiple ‘representations’. Long-term state maintained by the ‘resources’. In our case: –‘verbs’ are HTTP methods (GET, POST, PUT, DELETE) –‘nouns’ are URLs (e.g. /posts/1). –‘representations’ are formats (HTML, XML, RSS, JSON, etc.)

REST cont. Why is this useful? Useful for networking components to know when they can cache responses. Rather than using the URL to indicate the action (e.g. ‘/posts/get_article/1’), have standard action (HTTP GET) applied to a resource (e.g. ‘posts/1’). Generalizes to other resources (e.g. we know what happes if we do an HTTP GET for ‘/users/1’). But at some level, I don’t get the fuss.

REST in Rails Rails is set up for ‘RESTful’ applications. Can see the routes created by “map.resources :posts” by typing ‘rake routes’.

HTTP methodURLAction GET/postsindexLists all posts GET/posts/:idshowShow post :id GET/posts/:id/editeditEdit post :id GET/posts/newnewMake new post (form input) PUT/posts/:idupdateUpdate post :id using info from request DELETE/posts/:iddestroyDelete post :id POST/postscreateMake new post using info from request

posts_controller.rb We can see the actions in the controller: def = Post.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml } end def = Post.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml } end

XML Note that there is built-in support for an XML representation; try browsing ‘ ’.

ERB Now some of the.erb files make more sense. index.html.erb: 'Are you sure?', :method => :delete %>

ERB Any Ruby inside “ ” gets executed. E.g. Any Ruby inside “ ” gets executed, the result turned into a string, and displayed. E.g. ‘h’ is a method that displays special characters correctly in HTML; like PHP htmlentities().

ERB ‘link_to’ a method for creating links. edit_post_path(post), new_post_path methods automatically created to return URLs to the ‘edit’ and ‘new’ actions of the posts_controller. Note in ‘Destroy’ link we have to specify the HTTP method ‘:delete’. 'Are you sure?', :method => :delete %>

Partials

With ‘partials’, we can create ‘partial’ views that can be rendered inside other views. A bit like a PHP ‘include’. The file name of a partial is prefixed with an ‘_’.

Let’s try one… Notice that app/views/posts/new.html.erb and app/views/posts/edit.html.erb are almost identical. Let’s capture the common part in a partial.

_form.html.erb Create a new file ‘app/views/posts/_form.html.erb’. Copy the following from ‘app/views/posts/edit.html.erb’ into ‘_form’:

Now edit blog/app/views/posts/edit.html.erb by replacing the removed code with: ‘form’ %> and the same for blog/app/views/posts/new.html.erb. Now try the blog…

Problem… The submit button says ‘Create’ for both entering a new entry and editing an old one. We can solve this by passing in local variables to each…

Edits _form.html.erb; change f.submit line to new.html.erb; change render line to 'form', :locals => {:action => 'Create'} %> edit.html.erb; change render line to 'form', :locals => {:action => 'Update'} %>

Review

Reminders…