Model View Controller architecture MVC is a software architecture by oneforseven

VIEWS: 834 PAGES: 16

									Model-View-Controller architecture
MVC is a software architecture that seperates an applications data model, user interface and control logic into three distinct components.
Model The domain-specific representation of the information on which the application operates. Business rules, data constraints and relations are implemented in this component. Encapsulation of the domain logic. View Renders the model into a form suitable for interaction, typically a user interface element. In web applications, the view is usually the HTML page which gathers dynamic data for the page. Controller Processes and responds to events, typically user actions, and invokes changes on the model and perhaps the view.

The database structure is not described, it is assumed to be encapsulated by the Model.
CS 242 - Databases

Ruby on Rails
Ruby
Programming language created in 1990’s by Yukihiro ”Matz” Matsumoto Read (for background and example code)
http://en.wikipedia.org/wiki/Ruby programming language

Rails framework (for Ruby)
Created by David Heinemeier Hansson, released in 2004. Convention over Configuration:
If you use standard Rails code conventions, you don’t have to define anything. If there is a Painting model, bindings are automatically made to the table paintings in the (MySQL) database If the model name Canvases is used, the break from convention requires that set table name "paintings" be done in the model.

Don’t Repeat Yourself (DRY)
Definitions should only be made once. Components (MVC) are integrated so that bridges between them do not need to be set up. E.g. column names need not be specified, as they can be found using the database.
CS 242 - Databases

Rails Conventions
Models
Class names in singular, camelized form, e.g. FlightLeg. File names in singular form, -seperated lowercase, e.g. flight leg.rb.

Controller
Class names in singular, camelized form with Controller appended, e.g. FlightLegController. File names in singular, -seperated lowercase form with controller appended, e.g. flight leg controller.rb.

Views
Contained in seperate files in subdirectory of /views named after singular, -seperated lowercase form
E.g. /views/flight leg/

File names in this subdirectory follow names of actions defined in controller (see next slides)

CS 242 - Databases

Rails Conventions, continued
Database structure
Table names are plural form, -seperated lowercase
e.g. painters and paintings.

Primary keys of all tables are named id and are of type int. Foreign key references in the child table are made through an attribute named after the singular lower-case form of the parent table (with id appended)
E.g. the table paintings will contain an attribute (column) painter id of type int, acting as a FK reference to attribute id of table painters.

If a bridge entity is required for a M:N relationship (e.g. between the students and courses tables), a database table with the -seperated concatenation of their names in alphabetical order must be created
E.g. add the table courses students to the database, containing columns course id and student id acting as FKs.

CS 242 - Databases

Example: Creating a Rails web application
From the shell:
rails appname cd appname

Creating models:
./script/generate model Student ./script/generate model Course

Creating controllers:
./script/generate controller Students <list of actions>

Alternatively, generate scaffolding (generates controllers and views):
./script/generate scaffold Student student <list of actions> Usage: ./script/generate scaffold ModelName ControllerName [action, ...]

Starting the WEBrick server:
./script/server
CS 242 - Databases

Rails’ MVC architecture : Models
Consists of classes representing RDBMS tables Model classes are handled through ActiveRecord (subclass ActiveRecord::Base) ActiveRecord is the object-relational mapping (ORM) layer that connects business objects (models) to database tables. Class definitions specify relations between classes (i.e. relations between database tables)
class Painter < ActiveRecord::Base has many :paintings end class Painting < ActiveRecord::Base belongs to :painter end

Data validation handlers, e.g.
validates uniqueness of :painterphoto

Update-related handlers, e.g.
before destroy :remove paintings
CS 242 - Databases

Rails’ MVC architecture : Models - Relationships
Examples of relationship types in ActiveRecord models
Lecturer-Office is 1:1, Lecturer-Course is 1:M, Student-Course is M:N

class Lecturer < ActiveRecord::Base has many :courses belongs to :office end class Office < ActiveRecord::Base has one :lecturer end class Course < ActiveRecord::Base belongs to :lecturer has and belongs to many :students end class Student < ActiveRecord::Base has and belongs to many :courses end
CS 242 - Databases

Rails’ MVC architecture : Models - Relationships, cont’d
Given the model definitions of the previous slide, we can write the following Ruby on Rails code:
some course = Course.find(10) some course contains the row of courses table with id=10 some courses = Course.find by department("CS") some courses contains a collection of rows from courses table with department=”CS”. all courses = Course.find(:all) some students = some course.students some lecturer = some course.lecturer some lecturers courses = some lecturer.courses or:
some lecturers courses = Course.find(10).lecturer.courses

Attributes:
some lecturer.fname, some lecturer.lname, some lecturer.id (= 10), some lecturer.salary .
CS 242 - Databases

Rails’ MVC architecture : Controllers
Classes derived from ApplicationController Consists of actions (methods available from UI) For example, /controllers/time controller.rb:
class TimeController < ApplicationController def now render :text => "The time is #{Time.now}." end end

As these actions are available to the views (more about that later), they can be executed using
http://address/controller/action/params

For example:
http://localhost:3000/time/now

CS 242 - Databases

Rails’ MVC architecture : Controllers, continued
Some scaffold-generated controller code (/controllers/student controller.rb):
class StudentController < ApplicationController def index render :action => ’list’ end def list @students = Student.find(:all, :order => "age ASC") end def show @student = Student.find(params[:id]) end def new @student = Student.new end end

When http://localhost:3000/student/show/10 is accessed:
The instance variable @student is set to be the row in the students table with id = 10.
CS 242 - Databases

CS 242 - Databases

Rails’ MVC architecture : Views
Match names of actions in corresponding controller For example:
The view /views/student/show.rhtml corresponds to the show action in the controller /controllers/student controller.rb.

A Rails view is HTML code with dynamic Ruby code included inside <% and %>. For example, /views/student/show.rhtml:
<html> <body> Student <%= @student.fname+" "+@student.lname %>: <ul> <li>Age:<%= @student.age.to s %></li> <li># of courses:<%= @student.courses.count.to s %></li> <li>Date of birth:<%= @student.dob.to s %></li> </ul> </body> </html>

CS 242 - Databases

Rails’ MVC architecture : Views, continued
For example, /views/student/list.rhtml:
<html> <body> <h1>List of Students</h1> <table> <tr> <th>Name</th><th>ID Number</th><th>Birthday</th> </tr> <% for student in @students %> <tr> <td><%= student.fname+" "+student.lname %></td> <td><%= student.idnumber.to s %></td> <td><%= student.dob.to s %></td> <%= link to "Show",{:action => :show},:id => student.id %> </tr> <% end %> </table> </body> </html>
CS 242 - Databases

Methods in Models
In Model: (/models/student.rb)
class Student < ActiveRecord::Base has and belongs to many :courses def has enough subjects? return (self.courses.count >= 6) end end

In View: (/views/student/show.rhtml)
<html> <body> Student <%= @student.fname+" "+@student.lname %>: <ul> <li>Age:<%= @student.age.to s %></li> <li># of courses:<%= @student.courses.count.to s %></li> <li>Date of birth:<%= @student.dob.to s %></li> <% unless @student.has enough subjects? %> <li>This student is not taking enough subjects.</li> <% end %> </ul> </body> </html>
CS 242 - Databases

Join Models
Suppose we want a M:N relationship, but with more information stored in the bridge entity. For example: Students, Courses and Enrollments.
class Enrollment < ActiveRecord::Base belongs to :student belongs to :course end class Student < ActiveRecord::Base has many :enrollments, :dependent => :destroy has many :courses, :through => :enrollments end class Course < ActiveRecord::Base has many :enrollments, :dependent => :destroy has many :students, :through => :enrollments end

:dependent can be used in any parent entity, and set to :destroy, :nullify or :delete all. See http://wiki.rubyonrails.org/rails/pages/ThroughAssociations
CS 242 - Databases

Things to do
Read
http://wiki.rubyonrails.com/rails/pages/UnderstandingMVC

Watch rails take2 with sound.mov - screencast of David Heinemeier Hansson writing a simple blog in Rails in 15 minutes. API reference: http://api.rubyonrails.org Validation rules in model Find by SQL
Student.find by sql ["SELECT * FROM students WHERE dob > ?", some date]

User interface building for M:N relations
See has many and belongs to many.pdf on CD.

Optional, but useful things when developing Rails applications
Helpers Partials Plugins Migrations
CS 242 - Databases


								
To top