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.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
Advertisements

Session 2Introduction to Database Technology Data Types and Table Creation.
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.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)MySQL Recap.
Let’s try Oracle. Accessing Oracle The Oracle system, like the SQL Server system, is client / server. For SQL Server, –the client is the Query Analyser.
Maintenance Modifying the data –Add records –Delete records –Update records Modifying the design –Add fields into tables –Remove fields from a table –Change.
CS 142 Lecture Notes: Rails ActiveRecordSlide 1 Model for Student Table SELECT * FROM students; | id | name.
CS 683 Emerging Technologies Fall Semester, 2005 Doc 24 Rails Database Nov 22, 2005 Copyright ©, All rights reserved SDSU & Roger Whitney, 5500 Campanile.
Introduction to Databases CIS 5.2. Where would you find info about yourself stored in a computer? College Physician’s office Library Grocery Store Dentist’s.
CS 683 Emerging Technologies Fall Semester, 2005 Doc 22 Rails Basic Action Pack & Active Record Nov 15, 2005 Copyright ©, All rights reserved SDSU.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Ruby on Rails: An Introduction JA-SIG Summer Conference 2007 Michael Irion The University of Tulsa.
RUBY ON RAILS Mark Zhang. In this talk  Overview of Ruby on Rails  Core ideas  Show a tiny bit of example code  Touch on several general web development/
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,
MySql In Action Step by step method to create your own database.
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.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
INTERNET APPLICATION DEVELOPMENT For More visit:
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
MVC & ActiveRecord by Christian Mohr & Mohamed Souiai.
1 Dr Alexiei Dingli Web Science Stream Advanced ROR.
PHP meets MySQL.
® Microsoft Access 2010 Tutorial 1 Creating a Database.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Introduction to Internet Databases MySQL Database System Database Systems.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Database Fred Durao What is a database? A database is any organized collection of data. Some examples of databases you may encounter in.
© Copyright IBM Corporation 2007 AP/Americas April 15-18, 2007 Anaheim, California Introduction to RubyOnRails - a J2EE replacement? Russell Scheerer –
M1G Introduction to Database Development 2. Creating a Database.
Associations INFO 2310: Topics in Web Design and Programming.
CS 142 Lecture Notes: Rails ActiveRecordSlide 1 Model for Student Table SELECT * FROM students; | id | name.
CS 142 Lecture Notes: Rails ActiveRecordSlide 1 Model for Student Table SELECT * FROM students; | id | name.
Ruby on Rails: Databases. Rails Database Familiar Table Concept Naming convention – lower case, plural (i.e. tweets) How to Access (find), Update, Delete.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
SESSION 3.1 This section covers using the query window in design view to create a query and sorting & filtering data while in a datasheet view. Microsoft.
® Microsoft Office 2013 Access Creating a Database.
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.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
CS 142 Lecture Notes: Rails ActiveRecordSlide 1 Model for Student Table SELECT * FROM students; | id | name.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CS 142 Lecture Notes: FormsSlide 1 Simple Form Product: Price:
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.
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
A am going to create a table in design view. I am going to create a table in an Access database that contains information about the books that I have on.
Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.
Migrations Carol Wolf CS 396X. ISBNTitleAuthorImage EmmaAustenemma.jpg Oliver TwistDickenstwist.jpg HamletShakespearehamlet.jpg.
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.
CS320 Web and Internet Programming SQL and MySQL Chengyu Sun California State University, Los Angeles.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
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.
Introduction to Databases & SQL Ahmet Sacan. What you’ll need Firefox, SQLite plugin Mirdb and Targetscan databases.
COM621: Advanced Interactive Web Development Lecture 10 PHP and MySQL.
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
Ruby on Rails Model of MVC
ISC440: Web Programming 2 Server-side Scripting PHP 3
Agile Web Development with Ruby and Rails
Model for Student Table
Chapter 15 Introduction to Rails.
CS3220 Web and Internet Programming SQL and MySQL
Model for Student Table
CS3220 Web and Internet Programming SQL and MySQL
Presentation transcript:

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 Code Reusability Making it clear where different types of code belong for easier maintenance

MVC Model - the information (data) of the application and the rules to manipulate that data. Business logic View – takes data and displays it Controller – the glue between the model and controller. In Rails, they’re responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.

Models the information (data) of the application and the rules to manipulate that data. Business logic should be concentrated here. Models are usually related to tables in a database. Model’s attributes are “columns”. But not always. Models that are not related to database tables are transient. EXAMPLE: If a model is related to a table, the table’s name will be “line_items” for model LineItem, for example. Demo: app/model/user.rb

Model Class – representing a database table Database table example: Name of table = tweets Has keys of id, status and zombie where id is unique, primary key

Model Class – representing a database table Now, lets create a Model class associated with our database table tweets. GIVE IT NAME Uppercase, singual = Tweet Stored in app/models/tweet.rb class Tweet < ActiveRecord::Base end

Model Class – representing a database table entry Our Class Tweet is mapped to database tweets automatically by naming convention

What is Activation Record An Object that wraps a row in a database table or view, encapsulates the database access, adds domain logic on that data "Martin Fowler" require "rubygems" require_gem "activerecord" #Connect ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :database => "cs683BookStore_development", :username => "whitney") class Book < ActiveRecord::Base end CREATE TABLE `books` ( `id` int(11) NOT NULL auto_increment, `title` varchar(100) NOT NULL default '', `author` varchar(50) NOT NULL default '', `date` date default ' ', PRIMARY KEY (`id`) ) Suppose you have the following database table – maybe in mysql (could be others) You would replace this with YOUR database’s info MODEL class for books table General Code using Model Book #Add to database ruby = Book.new ruby.title = 'Programming Ruby' ruby.author = 'Thomas, Dave' ruby.date = Time.now ruby.save from_database = Book.find_by_title('Programming Ruby') puts from_database.author

a = Book.find_by_title('Programming Ruby') a = Book.find_by_author('Thomas, Dave') a = Book.find_all_by_author('Thomas, Dave') a = Book.find_by_sql("select * from Books where author = 'Thomas, Dave' ") a = Book.find(:first, :conditions => "author = 'Thomas, Dave'") a = Book.find(:first, :conditions => [ "author = 'Thomas, Dave' and title = 'Programming Ruby'"]) a = Book.find(:all, :conditions => [ "author = 'Thomas, Dave'"]) name = 'Thomas, Dave' a = Book.find(:first, :conditions => [ "author = ?", name]) More Examples (now with Book Model) to find database entries

ruby = Book.new ruby.title = 'Programming Ruby' ruby.author = 'Thomas, Dave' ruby.date = Time.now ruby.save aBook = Book.new( :title => 'Programming Ruby', :author => 'Thomas, Dave', :date => Time.now ) aBook.save aBook = Book.create( :title => 'Programming Ruby', :author => 'Thomas, Dave', :date => Time.now ) params = { :title => 'Programming Ruby', :author => 'Thomas, Dave', :date => Time.now} aBook = Book.create(params) More Examples (now with Book Model) to create database entry

Well… how do you actually create a new Model class in Rails You use a generation tool…….lets look

How do you create a Model class in Rails Command Line rails generate model name_model_class RubyMine IDE Tools-> Run Rails Generator -> model >>> give it the name of the model class (like user or students or book) What is generated 2 files: 1) app/models/name.rb this is the model class file 2) db/migrate/*_create_nameS.rb this is a database file you can use to create corresponding table (see lecture on database on how to edit this to create a

Using the db/migrations/*_create_modelnameS.rb file to create the underlying database table Using our previous User example edit the file db/migrations/*_create_users.rb class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.column :first_name, :string t.column :last_name, :string t.timestamps null: false end end end idfirst_namelast_name Primary keystring “users” database table

Validating Being Careful when you create a new database entry ---you don’t want blank entries after all or worse?

Model Class -- validating Make sure you don’t want to create a new database entry using our Model class that has certain keys empty. You do this by setting validates_presence_of :key in the Model class

Model Class – other validations validates_presence_of :key if key value is specified validates_numericality_of :key if key value is numerical validates_uniqueness_of :key if key value is unique validates_length_of :key, minimum: 3 if key value has length at least 3 validates_inclusion_of :key, in: if key value is between 9 to 31

Relationship between Models Database tables can have relationships between them. Think of Tweet and Zombie. A Zombie can have many Tweets and a Tweet has only one Zombie

2 tables with Relationships – yields 2 Model classes First say we have 2 tables

Zombie Class First, each Zombie class instance (database entry) can have 0 to many Tweet entries In apps/models/Zombie.rb class Zombie < ActiveRecord::Base has_many: tweets end Note: you say has_many: tablename not the corresponding Class name

Zombie Class First, each Tweet class instance (database entry) can have only 1 corresponding Zombie In apps/models/Tweet.rb class Tweet < ActiveRecord::Base belongs_to: zombie end Note: you say SINGULAR zombie

Creating New Tweet for the Zombie with name Ash First get Zombie Ash, Then create Tweet passing it the Zombie Ash ---it will setup the zombie_id field for you Start: Ash has 2 tweets

The new Tweet in database tweets

Model Class – other validations ALTERNATIVE validates :key, type: value EXAMPLE validates :status, presence: true if they status’s value is not nill EXAMPLE 2 validates :status, length: {minimum: 3} if they status’s value has minimum length of 3

One more example for the road The Student Model and corresponding students table

Model for Student Table SELECT * FROM students; | id | name | birth | gpa | grad | | 1 | Anderson | | 3.9 | 2009 | | 2 | Jones | | 2.4 | 2012 | | 3 | Hernandez | | 3.1 | 2011 | | 4 | Chen | | 3.2 | 2011 | Rails model class ( app/models/student.rb) : class Student < ActiveRecord::Base end Command to create this class: rails generate model student

How you can Create New Record--- maybe inside a Controller class’s method somewhere (we will discuss Controllers later) student = Student.new student.name = "Williams" student.birth = " " student.gpa = 2.8 student.grad = 2012 student.save()

Well here is a peak ( you don’t understand yet) at some controller code That asks to get All students in the database table app/controllers/students_controller.rb: class StudentsController < ApplicationController... def = Student.all end end REQUEST: This will call the StudentsController.index method

Here is a View that will be invoked by previous Controller’s index method app/views/students/index.html.erb: Current Students Name Date of Birth GPA Graduation Year "> :edit, :id => student.id) %> NOTE: The was defined in Controller on previous slide. It contains instances of Student Model class –each one representing a different entry in the students database table

Student Model: Read, Update, Delete students = Student.all() student = Student.find(187) student = Student.find_by(name: "Hernandez") student = Student.find_by_name("Hernandez") smarties = Student.where("gpa >= 3.0") smarties = Student.order("gpa DESC").limit(10) student = Student.find(187) student.gpa = 4.0 student.save() Student.find(187).destroy() AGAIN: This code would be in a Controller class’s method(s)