Chapter 15 © 2013 by Pearson. 1 15.1 Overview of Rails - Rails is a development framework for Web-based applications - Based on MVC architecture for applications.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
WEB DESIGN TABLES, PAGE LAYOUT AND FORMS. Page Layout Page Layout is an important part of web design Why do you think your page layout is important?
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.
Chapter 15 © 2010 by Addison Wesley Longman, Inc Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in Use spread rapidly.
Creating Web Services with Ruby on Rails Robert Thew Internet and Web Systems II.
Creating rails app. p:\InstantRails\rails_apps>rails -d mysql cars create create app/controllers create app/helpers create app/models create app/views/layouts.
The Web Warrior Guide to Web Design Technologies
Ruby on Rails by Manik Juneja Ruby On Rails. Ruby on Rails by Manik Juneja Rails is a Web Application development framework. Based on the MVC pattern.
1 Chapter 12 Working With Access 2000 on the Internet.
J4www/jea Week 3 Version Slide edits: nas1 Format of lecture: Assignment context: CRUD - “update details” JSP models.
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.
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.
Ruby on Rails Creating a Rails Application Carol E Wolf CS396X.
Chapter 2 Introduction to HTML5 Internet & World Wide Web How to Program, 5/e Copyright © Pearson, Inc All Rights Reserved.
Ruby on Rails: An Introduction JA-SIG Summer Conference 2007 Michael Irion The University of Tulsa.
INTRODUCTION TO WEB DATABASE PROGRAMMING
Website design Feng Zhao College of Educatioin California State University, Northridge.
Chapter 4 Dreamweaver: Part II The Web Warrior Guide to Web Design Technologies.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
NextGen Technology upgrade – Synerizip - Sandeep Kamble.
Rails and Grails. To get started Make sure you have java installed You can get the sdk and jre at:
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
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.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
1 Dr Alexiei Dingli Web Science Stream Models, Views and Controllers.
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
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
Chapter 1: Introduction to Web
Server-side Scripting Powering the webs favourite services.
XP New Perspectives on Browser and Basics Tutorial 1 1 Browser and Basics Tutorial 1.
Ajax and Ruby on Rails Session 9 INFM 603.
10 Adding Interactivity to a Web Site Section 10.1 Define scripting Summarize interactivity design guidelines Identify scripting languages Compare common.
1 Dr Alexiei Dingli Web Science Stream Introducing Rails.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
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.
COM531 Multimedia Technologies
Copyright 2007, Information Builders. Slide 1 Understanding Basic HTML Amanda Regan Technical Director June, 2008.
Chapter 8 Collecting Data with Forms. Chapter 8 Lessons Introduction 1.Plan and create a form 2.Edit and format a form 3.Work with form objects 4.Test.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Chapter.
Associations INFO 2310: Topics in Web Design and Programming.
Chapter 15 © 2009 by Addison Wesley Longman, Inc Overview of Rails - Rails is a development framework for Web-based applications - Rails is written.
HTML Basics BCIS 3680 Enterprise Programming. Web Client/Server Architecture 2  Your browser (the client) requests a Web page from a remote computer.
Dynamic web content HTTP and HTML: Berners-Lee’s Basics.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
Web Development 101 Presented by John Valance
Web Design and Development. World Wide Web  World Wide Web (WWW or W3), collection of globally distributed text and multimedia documents and files 
Module: Software Engineering of Web Applications Chapter 2: Technologies 1.
Introduction to HTML. _______________________________________________________________________________________________________________ 2 Outline Key issues.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Introduction to Ruby&Rails Yuri Veremeyenko Monica Verma.
CP476 Internet Computing Perl CGI and MySql 1 Relational Databases –A database is a collection of data organized to allow relatively easy access for retrievals,
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
Rails and routing INFO 2310: Topics in Web Design and Programming.
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 to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.
CS 160 and CMPE/SE 131 Software Engineering February 11 Class Meeting Department of Computer Science Department of Computer Engineering San José State.
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.
Advanced Migration By Aye Mon Tun.  To change database schema in consistent and easy way  In ruby code Migration? 11/25/2013 2Web Application Engineering.
Teaching slides Chapter 6. Chapter 6 Software user interface design & construction Contents Introduction Graphical user interface – Rich window based.
Introduction to RoR Ruby on Rails
Introduction to RoR Ruby on Rails
Play Framework: Introduction
Ruby on Rails by Manik Juneja
Ruby on Rails by Manik Juneja
Chapter 15 Introduction to Rails.
Presentation transcript:

Chapter 15 © 2013 by Pearson Overview of Rails - Rails is a development framework for Web-based applications - Based on MVC architecture for applications - MVC cleanly separates applications into three parts: - Model – the data and any restraints on it - View – prepares and presents results to the user - Controller – controls the application - One characterizing part of Rails is its approach to connecting object-oriented software with a relational database – ORM - Maps tables to classes, rows to objects, and columns to fields of the objects

Chapter 15 © 2013 by Pearson Overview of Rails (continued) - View documents are HTML documents that may include Ruby code - A Rails application is a program that provides a response when a client browser connects to a Rails-driven Web site - Rails can be used with Ajax - Two fundamental principles that guided the development of Rails: 1. DRY 2. Convention over configuration - Rails does not use a GUI - Rails is included in versions or later of Ruby - We use SQLite 3, so it must be downloaded and installed ( )

Chapter 15 © 2013 by Pearson Document Requests - After creating a subdirectory for our Rails applications, examples, in the Ruby bin directory, we create our first application in that subdirectory named greet >rails new greet - This creates the framework for the new application - The created app subdirectory has four subdirectories, models, views, controllers, and helpers - Rails provides the generate script, which is used to create part of the controller for the application, as well as a subdirectory of the views directory for the view documents of the application - generate needs three parameters - controller - a name for the controller - a name for an action method in the controller (which is also the name of the view markup file) >rails generate controller say hello

Chapter 15 © 2013 by Pearson Document Requests (continued) - Static Documents (continued) - There are now two files with empty classes in the controller directory, say_controller.rb : application.rb has ApplicationController say_controller.rb has SayController class SayController < ApplicationController def hello end - The SayController class produces, at least indirectly, responses to requests - The URL of our Rails application is - The Rails-generated view document: say#hello Find me in app/views/say/hello.html.erb

Chapter 15 © 2013 by Pearson Document Requests (continued) - Static Documents (continued) <!-- hello.html.erb - the template for the greet application --> greet Hello from Rails - To test the application, a Web server must be started – we use webrick (included with Rails) >rails server webrick

Chapter 15 © 2013 by Pearson Document Requests (continued) - Static Documents (continued) - Response activities: 1. Instantiate SayController class 2. Call the hello action method 3. Search the views / say directory for hello.html.erb 4. Process hello.html.erb with Erb 5. Return the resulting hello.html.erb to the requesting browser

Chapter 15 © 2013 by Pearson Document Requests (continued) - Dynamic Documents - Dynamic documents can be built with Rails by embedding Ruby code in the template document - An example: display a greeting and the current date and time and the number of seconds since midnight - Ruby code is embedded in a document by placing it between - To insert the result of evaluating the code into the document, use <%= - The Time class has a method, now, that returns the current day of the week, month, day of the month, time, time zone, and year, as a string It is now Number of seconds since midnight:

Chapter 15 © 2013 by Pearson Document Requests (continued) - Dynamic Documents (continued) - It would be better to put the code in the controller def = * 3600 * 60 end - Now the Ruby code in the template is: It is now Number of seconds since midnight:

Chapter 15 © 2013 by Pearson Rails Applications with Databases - Use a simple database with just one table - The application will be named cars - The application will present a welcome document to the user, including the number of cars in the database and a form to get the beginning and ending years and a body style for the desired car - Creating the application - In the subdirectory of our examples: >rails new cars - Build the model, migration script, database table, and maintenance controller for the database >rails generate scaffold corvette body_style:string miles:float year:integer - corvette is the name of the model (by convention the name of the table is the plural form of the name of the model)

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - The migration class file built by this in cars/db/migrate is: class CreateCorvettes < ActiveRecord::Migration def change create_table :corvettes do |t| t.string :body_style t.float :miles t.integer :year t.timestamps end - We do not have a database—only the description (a migration class) of a database - To create the database, use rake : >rake db:migrate - This causes the execution of the change method (in C:/Ruby192/bin/examples/cars) == CreateCorvettes: migrating============== -- create_table(:corvettes) -> s == CreateCorvettes: migrated (0.0020s) ====

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - The controller for the application is named corvettes, so we can see the application at - Rails built the basic table maintenance operations, create, read, update, and delete (CRUD) - If we click New corvette, we get:

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - If we fill out the form, as in: - Now we click Create, which produces:

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Now if we click Back, we get: - If we click Edit, we get:

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - If we click Destroy, we get: - The model file, which is in cars/models, has the empty class: class Corvette < ActiveRecord::Base end - We can easily add some validation to this class by calling validates ; the last parameter specifies the kind of validation validates :body_style, :miles, :year :presence => true

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) validates :year, numericality => { :greater_than => 1952, :less_than_or_equal_to => Time.now.year} - The model class is now: class Corvette < ActiveRecord::Base validates :body_style, :miles,:year, presence => true validates :year, numericality => { :greater_than => 1952, :less_than_or_equal_to => Time.now.year} end - The controller built by Rails, named CorvetteController, provides the action methods: index – creates a list of rows of the table show – creates the data for one row new – creates a new row object edit – handles editing a row create – handles row creation update – handles updating a row delete – handles row deletion

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - There are four documents in the views directory, index.html.erb, new.html.erb, show.html.erb, and edit.html.erb ; here is index.html.erb : Listing corvettes Body style Miles Year <%= link_to 'Edit', edit_corvette_path(corvette) %>

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Notice that index.html.erb is only the content of the body element - The rest of the document comes from a layout document, which is stored in the layout subdirectory of views – built by scaffold Cars - yield is the place the template file belongs - The style sheet was furnished by scaffold - Any JavaScript files are stored in public/javascripts

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - The new.html.erb and _form.html.erb documents: ( new and edit both use _form.html.erb ) New corvette <%= "error") %> prohibited this corvette from being saved:

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - The show.html.erb document is: Body style: Miles: Year: <%= link_to 'Edit', %> | - The edit.html.erb document is: Editing corvette |

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Now we must build the actual application - Build a second controller for the required processes >rails generate controller main welcome # main_controller.rb - for the cars application class MainController < ApplicationController # welcome method – fetches values for the # initial view def = Corvette.count end - The count method of the table classes returns the number of rows in the table

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - To implement the searches of the table, use where - The where method searches a table for a specific row or rows mycar = Corvette.where(:body_style => "convertible") The RecordNotFound exception is thrown if where is asked to do something it cannot do - The qualifiers first, last, or all can be attached to the call to where ( first is the default) - Multiple conditions can be specified: sixty_five_conv = Corvette.where([ :year = 1965,:body_style = 'convertible’]).all - To use find with non-literal conditions, a different parameter form is needed my_year_conv = Corvette.where([ "year = ? and body_style =

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Next, design the welcome template, which has two tasks: 1. Display text boxes to get the model years and body style of interest from the user 2. Display the number of cars furnished by the welcome action method in the controller <!– welcome.html.erb – initial view for the cars application --> Aidan’s Used Car Lot Welcome to our home document We currently have used Corvettes listed To request information on available cars, please fill out the following form and submit it <!– The form to collect input from the user about their interests --> From year: <input type = "text" size = "4" name = "year1" /> To year: <input type = "text" size = "4" name = "year2" /> Body style: <input type = "text" size = "12" name = "body" />

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Next, design the result action method, which is named result in the welcome template form - Task: get form data and use find to compute the required output data for the result template - The form data is made available by Rails through a hash-like object params - params can be indexed by either keys or symbols If phone is the name of a control, we can = params[:phone] - The result method of the main controller is: # result method - fetches values for the result # template def = = = = Corvette.where( ["year >= ? and year <= ? and body_style @body]).all end

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Last step: build the result template document - Put the information about cars in a table Cars from to with the body style Body Style Miles Year do |car|

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - A filled out request: - The result document:

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Modifying a database - Rails was designed for agile development, so it makes it easy to change to new versions of databases, and also to revert back to earlier versions - The name of the initial version of the migration for the corvettes table was _create_corvettes.rb (it is in db/migrate ) - To change a database table, a new migration file is created and rake is used to update the table - To illustrate a change, we add a state column to the corvettes table - To create the new migration file: >rails generate migration AddStateToCorvette state:string - Produces the response: invoke active_record create db/migrate/ _add_state_to_corvette.rb

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Modifying a database (continued) - The resulting migration class, named _add_state_to_corvette.rb : class AddStateToCorvette < ActiveRecord::Migration def change add_column :corvettes, :state, :string end - Now use rake to apply the migration to the table: >rake db:migrate - Rails response: (in c:\Ruby192\bin\examples\cars) == AddStateToCorvette: migrating ============ -- add_column(:corvettes, :state, :string) -> s == AddStateToCorvette: migrated (0.0010s) ===

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - Modifying a database (continued) - Now the display of corvettes is: - To go back to the last migration form: >rake db:rollback - To go back to a specific migration: >rake db:migrate VERSION= Layouts - Rails provided one for the corvettes controller - We could build one for the main controller - Include the DOCTYPE, some headings, and a footer for a copyright

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) <!-- main.htm.erb – a layout for the main controller of cars --> Main Aidan's Used Car Lot Welcome to our home document Copyright 2012, AUCL, Inc. - We could also add a stylesheet for the templates of main - Could be used for both the actual template file and the layout /* mainstyles.css - a style sheet for the main controller */ h1 {font-style: italic; color: blue;} h2 {color: blue;}.labels {font-style: italic; color: red;} - Stored in cars/app/assets/stylesheets

Chapter 15 © 2013 by Pearson Rails Applications with Databases (continued) - To reference the stylesheet in the layout, add the following to the head of the layout document - Now the welcome template appears as: