Download L1 Introduction

Document related concepts

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Transcript
229-511 Web Application Development Technology
เทคโนโลยีสำหรับกำรพัฒนำโปรแกรมประยุกต์เว็บ
Suntorn Witosurapot
Phone: 074 287369 or
Email: [email protected]
November 2009
Lecture 4
Database’s Table Relationships
in Rails
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
2
Outline
• Review
– Rails & MVC
– Database & Data Modeling
• Rails and Databases
– Active Record Basics
– Mapping Cardinalities
– Migrations
• Exercise
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
3
Review: Rails
• Web Framework for Ruby
– Designed to make it easier to develop, deploy, and maintain
web applications
• Rails has a benefit in productivity
• Comparing with J2EE:
– J2EE currently has a benefit in scalability. If it’s a
client facing system for millions of concurrent
users – use J2EE.
– If it’s an internal web application, definitely take a
look at this technology as a possible way of
shortcutting the long development time for a J2EE
web app.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
4
Review: Rails (cont.)
Yes…they are fairly comparable….
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
5
Review: Database
• Migration: A powerful and flexible tool for
managing database changes
• Allows table, index, and data creation scripts
to be run in multiple environments with a very
simple syntax.
– Need to revert back to a previous DB version to
work on a bug? 1 command.
– Then refresh it back to the current dev version?
1 command.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
6
Example Migration
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
7
Review: MVC
• Model – Used for persistence & relationships
• View – Used for displaying the data
• Controller – The logic of the application
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
8
Rails and MVC
• Two Main components in Rails
– Action Pack and Active Record
• Active Record
– Create an idea of something in the database
– Has predefined function which can be used
– Don’t need to worry about underlying tech
• Action Pack
– Controller and View are tightly coupled
– Single Rails component
– View code and Controller code are separate
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
9
Database development process
Here, we will look at how to design a database that could be
implemented in a relational database product (e.g., MySQL)
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
10
Data Modeling
• A data model is a collection of concepts for
describing data.
• A schema is a description of a particular collection of
data, using a given data model.
• The relational model of data is the most widely used
model today.
• Main concept: relation, basically a table with rows
and columns.
• Every relation has a schema, which describes the
columns, or fields
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
11
Representing the Model
Techniques to Represent Aspects of the Data Model
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
12
Representing Classes and Attributes
To design a database table for each class:
• Class Attributes will become the field or column names of the table
• When the data is added, each row (or record) in the table will
represent an object
Case study: >>
Want to design a database
table for each class.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
13
Representing
Relationships
• the relationships between objects of different classes is
established using the foreign keys.
Foreign key field
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
14
Association between Tables
• Association represents relationship between
database tables, whose relationship is constructed
through foreign keys.
– They express relationships like "Project has one Project
Manager" or "Project belongs to a Portfolio".
• Cardinality relationship
– One-to-one: A person has a single primary address
– One-to-many: A school has many students
– Many-to-many: A course has many students and each
student take many courses.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
15
Outline
• Review
– Rails & MVC
– Database & Data Modeling
• Rails and Databases
– Active Record Basics
– Mapping Cardinalities
– Migrations
• Exercise
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
16
Active Record
• Object Relational Mapping (ORM) tool
supplied with Rails
• Maps
– Tables to classes
– Rows to objects
– Columns to object attributes
• determined at run time
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
17
Active Record Basics
• Create a subclass of ActiveRecord::Base
class Employee < ActiveRecord::Base
end
We don’t declare
the attributes
• Rails assumes that
– the name of the table is the plural form of the class name
– if the name contains multiple camel-case words, the table
name has underscores between the words
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
18
Active Record in Rails
• Active Record is used for Model
• Ex: ruby script/generate model person
– Will create app/models/person.rb
class Person < ActiveRecord::Base
end
– Maps to ‘people’ table in database
• Columns automatically map to class variables of the same name
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
19
CRUD & Other Stuff
•
•
•
•
•
Create
Read
Update
Delete
Other ActiveRecord Functions
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
20
Create
• Create row by creating object
an_order = Order.new
an_order.name = “Dave Thomas”
an_order.address = “122 Main”
an_order.phone = 2125551212
an_order.save
Order.new do |o|
o.name = “Dave Thomas”
o.address = “122 Main”
o.phone = 2125551212
o.save
end
229-511 Web Application Development
Technology
an_order = Order.new(
:name => “Dave Thomas”,
:address => “122 Main”,
:phone => 2125551212 )
an_order.save
Note: We didn’t need to set
a primary key. Rails
assumes “id” is primary key
and set auto-increment
Agile Programming, MVC Architecture & the
practice with RoR
21
Create
• Can also use create method
• Creates a new object and saves it
• Takes a hash or an array of hashes
an_order = Order.create(
:name => “Dave Thomas”,
:address => “122 Main”,
:phone => 2125551212 )
229-511 Web Application Development
Technology
an_order = Order.create(
[ { :name => “Dave Thomas”,
:address => “122 Main”,
:phone => 2125551212
},
{ :name => “Another Name”,
:address => “blah”,
:phone => 1234567890
}])
Agile Programming, MVC Architecture & the
practice with RoR
22
Read
• We need to specify which rows we want
– Rails will return objects containing the data from
those rows in the database
• Use the find method with one or more primary keys
– an_order = Order.find(27)
– product_list = Order.find(params[“product_list”])
• find() will throw a RecordNotFound exception if any of
the requested primary keys cannot be found
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
23
Read
• find() also has other options
– can pass :all or :first along with other parameters
• :conditions => “name = ‘Dave’”
– corresponds to WHERE clause
• :order => “name”
– corresponds to ORDER BY clause
• :limit => pagesize
– corresponds to LIMIT
• :offset => pagenum * pagesize
– use in connection with :limit to step through query results
• an_order = Order.find(:first,
:conditions => “name = ‘Dave Thomas’”)
• orders = Order.find(:all,
:conditions => “name = ‘Dave’”,
:order => “pay_type, shipped_at DESC”,
:limit => 10)
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
24
Read
• Allowing for externally generated parameters
– pname = params[:name]
orders = Order.find(:all,
:conditions => [“name = ?”, pname])
– orders = Order.find(:all,
:conditions => [“name = :name”,
{:name => pname}])
• Can also write your own SQL
– orders = Orders.find_by_sql(“select * from orders”)
• single parameter - SQL string
– Nice for hard queries or performance
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
25
Update
• Simple
– find the row or rows using find
– update necessary fields
– save
order = Order.find(123)
order.name = “Fred”
order.save
• Also works with an array for multiple update
– orders = Order.find(:all, :conditions => “name like ‘Dave%’”)
orders[0].name = “Fred”
etc.
• May also use update() or update_all()
– order = Order.update(123, :name => “F”, :address => “blah”)
• finds, updates, saves, and returns object
– result = Order.update_all(“set clause”, “where clause”)
• returns number of rows updated
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
26
Delete
• delete & delete_all
– Order.delete(123)
– Order.delete([1,2,3,4])
– Order.delete_all([“price > ?”, maxprice])
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
27
Other ActiveRecord Stuff
• Magic column names
– id
• primary key
– created_at, created_on, updated_at, updated_on
• automatically updated with timestamps
– xxx_id
• foreign key
• Find by value of a particular column
– Dynamically associates a find_by and find_all_by method
with each column
– order = Order.find_by_name(“Dave Thomas”)
– order = Order.find_by_address(“123 Main”)
– orders = Order.find_all_by_email(params[“email”])
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
28
Outline
• Review
– Rails & MVC
– Database & Data Modeling
• Rails and Databases
– Active Record Basics
– Mapping Cardinalities
– Migrations
• Exercise
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
29
Relationships between Tables
• Relationships are established using foreign keys
• Foreign key columns should be
– named using the singular form of the table name
with _id appended
– example: a foreign key for the table products
should be product_id
• This expresses relationship, but not the cardinality of
the relationship
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
30
Specifying Relationships
• Relationships are specified by adding declarations to
models
– has_one, has_many, belongs_to,
has_and_belongs_to_many
• Rule of thumb
– Foreign key always has the belongs_to declaration
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
31
One-to-one
Note: the model for the table that contains the foreign
key *always* has the belongs_to declaration
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
32
One-to-many
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
33
Many-to-many
Note: Many-to-many associations are symmetrical—
both of the joined tables declare their association with
each other using has_and_belongs_to_many.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
34
Relationship methods
• Relationship declarations also introduce
methods to the associated objects.
– dynamically created
– named using the table that it refers to
• Help navigate between the linked objects
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
35
Example
class Product < ActiveRecord::Base
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :product
end
Result:
Current product is 1
Programming Ruby
New product is 2
Rails for Java Developers
item = LineItem.find(2)
# item.product is the associated Product object
puts "Current product is #{item.product.id}"
puts item.product.title
item.product = Product.new(:title => "Rails for Java Developers" ,
:description => "..." ,
:image_url => "http://....jpg" ,
:price => 34.95,
:available_at => Time.now)
item.save! # save or raise exception
puts "New product is #{item.product.id}"
puts item.product.title
Note: ActiveRecord takes care of the details. It
created a new product and linked the LineItem
to it via the foreign key
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
36
Q: Is it a belongs_to or has_one association?
class User < ActiveRecord::Base
??????? :account
end
class Account < ActiveRecord::Base
?????? :user
end
Recall: It depends on where you place the foreign key, which goes on
the table for the class declaring the belongs_to relationship.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
37
Outline
• Review
– Rails & MVC
– Database & Data Modeling
• Rails and Databases
– Active Record Basics
– Mapping Cardinalities
• Exercise
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
38
Application Description:
A basic musician database
• Each artist will be one individual with a name, age,
and list of songs (not albums).
• Each song will have a title, duration and fit under one
genre (แนวเพลง).
• This design is assumed that
– an artist may consist of several individuals and may have
multiple albums containing multiple songs, and
– each song, artist and album can fit under a mesh of genres.
• Q1: How many entities are we keeping track of ?
• Q2: How many attributes are in each entity?
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
39
Identifying Entities & Attributes
We have the following entities and attributes:
• Artist: Has a name, age
and songs.
• Song: Has a title,
duration and fits under
one artist and one genre.
• Genre: Each has a name,
and houses many songs.
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
40
Creating our App (themusic)
• Open Ruby console a shell window
• Create an application called themusic, by typing as
Rails –d mysql themusic
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
41
Files & Folders created
• Many files and
folders will be
created for the
application.
• Change to our
app. directory
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
42
Create the Table structures using Scaffold
1. ruby script/generate scaffold artist
name:string age:integer
2. ruby script/generate scaffold genre
name:string
3. ruby script/generate scaffold song
title:string duration:integer artist_id:integer
genre_id:integer
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
43
Migration files
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
44
Create database & tables
1.
2.
rake db:create:all
rake db:migrate
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
45
Check whether the web app is ok?
• This is to make sure that everything is fine as it should be!
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
46
Adding
Relationships
Notice:
Songs is plural
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
47
Interacting with Our App Via Console
• Rather than using web interface, we will interact with
our app. via the ruby console
ruby script/console
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
48
Let’s begin
• Creating an instance of the Artist model. Type
the following and hit enter.
jb = Artist.new(:name => 'Joe Bloggs', :age => 22)
Simple Query:
>>
=>
>>
=>
jb.new_record?
true
jb.name
"Joe Bloggs“
229-511 Web Application Development
Technology
>>
=>
>>
=>
jb.age
22
jb.id
nil
Agile Programming, MVC Architecture & the
practice with RoR
49
Learning more
>> jb.songs
=> []
Q: Why?
Notice that the record
gets an ID after it is
saved:
>> jb.save
=> true
>> jb.id
=> 1
Save returns true on success.
>> tune = Song.new(:title => 'Love Me Three Times', :duration => 456)
=> #<song:0x2b420d56ec00 @attributes={"artist_id"=>nil, "title"=>"Love Me Three
Times", "genre_id"=>nil, "duration"=>456}, @new_record=true>
Trying to save our song as this point gives us errors:
>> tune.save
ActiveRecord::StatementInvalid: Mysql::Error: Column 'artist_id' cannot be null:
... long trace omitted ...
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
50
Learning more
Let’s create some genres on the fly.
>>
=>
>>
=>
>>
=>
>>
=>
>>
=>
Genre.new(:name =>
true
Genre.new(:name =>
true
Genre.new(:name =>
true
Genre.new(:name =>
true
Genre.new(:name =>
true
229-511 Web Application Development
Technology
'Bluegrass').save
'Goa Trance').save
'Doo Wop').save
'Blues Rock').save
'Emo').save
Agile Programming, MVC Architecture & the
practice with RoR
51
Learning more
• Assign the tune a genre:
>> tune.genre = Genre.find_by_name('Blues Rock')
• See that it has been set (don’t worry if your ID differs)
>>
=>
>>
=>
tune.genre.name
"Blues Rock“
tune.genre_id
4
• Use the Array object’s << operand
to append to Joe Blogg's song
array and then save it.
229-511 Web Application Development
Technology
>> jb.songs << tune
>> tune.save
=> true
Agile Programming, MVC Architecture & the
practice with RoR
52
>>
=>
>>
=>
>>
=>
Exploration
jb.songs[0].title
"Love Me Three Times"
tune.artist.name
"Joe Bloggs"
tune.artist_id
1
• Let’s fetch and create an instance of Joe Blogg’s
record from the database
>> bloggs = Artist.find_by_name('Joe Bloggs')
• Let’s explore
this object
further:
>>
=>
>>
=>
>>
=>
229-511 Web Application Development
Technology
bloggs.name
"Joe Bloggs"
bloggs.songs[0].title
"Love Me Three Times"
bloggs.songs[0].genre.name
"Blues Rock"
Agile Programming, MVC Architecture & the
practice with RoR
53
That’s the end
• You may try to add a few more artists and
songs to the database
• For closing the console, type “quit”
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
54
Complete our exercise
• Using browser, let create an artist, e.g. Joe Bloggs
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
55
Change the default page
Q: Which file does this screen generate?
A: index.html
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
56
Task: Add a link to browse songs of the artist
• This is what it should be displayed as in our plan
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
57
Task: Add a link to browse songs of the artist
(cont.)
Q: How should we modify the original file of index.html.erb?
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
58
Task: Add a link to browse songs of the artist
(cont.)
Answer: Step 1. Create code for link
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
59
Task: Add a link to browse songs of the artist
(cont.) Answer: Step 2. Create an action in the controller
• Add a method (also
called action)
called “browse” in
the artist controller
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
60
Task: Add a link to browse songs of the artist
(cont.) Answer: Step 3. Create a view file for the action
• Generate a method (also called action) called
“browse” in the artist controller
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
61
Result Screen
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
62
Backup
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
63
MySQL Workbench
• It is claimed a next-generation visual database design
application that can be used to efficiently design,
manage and document database schemata.
• This is extremely useful for drawing ER-diagram or
Class Diagram in UML.
• Just the Community Edition is OK & available from
http://dev.mysql.com/downloads/workbench/5.1.html
• The Windows version requires the .Net 2.0 framework
which is integrated with Windows Vista. Windows XP
SP2 users need to download the framework
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
64
Screenshots
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
65
Screenshots (cont.)
229-511 Web Application Development
Technology
Relationship Highlight
Agile Programming, MVC Architecture & the
practice with RoR
66
Screenshots (cont.)
Mouse right-click at any table
to edit table of attributes
229-511 Web Application Development
Technology
Agile Programming, MVC Architecture & the
practice with RoR
67
Screenshots (cont.)
229-511 Web Application Development
Technology
Export feature
Agile Programming, MVC Architecture & the
practice with RoR
68