Upload
tanisha-wood
View
22
Download
2
Embed Size (px)
DESCRIPTION
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. Outline. Review Rails & MVC Database & Data Modeling - PowerPoint PPT Presentation
Citation preview
229-511 Web Application Development Technology
เทคโนโลยี�สำ�หรั�บก�รัพั�ฒน�โปรัแกรัมปรัะยี�กต์�เว็�บ
Suntorn Witosurapot
Phone: 074 287369 or Email: [email protected]
November 2009
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 2
Lecture 4
Database’s Table Relationshipsin Rails
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 3
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 4
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 5
Review: Rails (cont.)
Yes…they are fairly comparable….
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 6
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 w
ork 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 7
Example Migration
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 8
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 9
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 10
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 11
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 12
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 13
Representing Classes and Attributes
Case study: >> Want to design a database
table for each class.
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
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 14
Representing Relationships
Foreign key field
• the relationships between objects of different classes is established using the foreign keys.
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 15
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 16
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 17
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 18
Active Record Basics
• Create a subclass of ActiveRecord::Baseclass Employee < ActiveRecord::Baseend
• 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
We don’t declarethe attributes
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 19
Active Record in Rails
• Active Record is used for Model• Ex: ruby script/generate model person
– Will create app/models/person.rbclass Person < ActiveRecord::Baseend
– 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 20
CRUD & Other Stuff
• Create• Read• Update• Delete• Other ActiveRecord Functions
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 21
Create
• Create row by creating objectan_order = Order.newan_order.name = “Dave Thomas”an_order.address = “122 Main”an_order.phone = 2125551212an_order.save
Order.new do |o| o.name = “Dave Thomas” o.address = “122 Main” o.phone = 2125551212 o.saveend
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
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 22
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 )
an_order = Order.create( [ { :name => “Dave Thomas”, :address => “122 Main”, :phone => 2125551212 }, { :name => “Another Name”, :address => “blah”, :phone => 1234567890 } ] )
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 23
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 24
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 25
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 26
Update
• Simple– find the row or rows using find– update necessary fields– 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
order = Order.find(123)order.name = “Fred”order.save
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 27
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 28
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 29
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 30
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 31
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 32
Note: the model for the table that contains the foreign key *always* has the belongs_to declaration
One-to-one
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 33
One-to-many
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 34
Note: Many-to-many associations are symmetrical—both of the joined tables declare their association with each other using has_and_belongs_to_many.
Many-to-many
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 35
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 36
Exampleclass Product < ActiveRecord::Base has_many :line_itemsendclass LineItem < ActiveRecord::Base belongs_to :productend
item = LineItem.find(2)
# item.product is the associated Product objectputs "Current product is #{item.product.id}"puts item.product.titleitem.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 exceptionputs "New product is #{item.product.id}"puts item.product.title
Current product is 1
Programming Ruby
New product is 2
Rails for Java Developers
Note: ActiveRecord takes care of the details. It created a new product and linked the LineItem to it via the foreign key
Result:
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 37
Q: Is it a belongs_to or has_one association?
Recall: It depends on where you place the foreign key, which goes on the table for the class declaring the belongs_to relationship.
class User < ActiveRecord::Base ??????? :accountend
class Account < ActiveRecord::Base
?????? :userend
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 38
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 39
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 40
Identifying Entities & 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.
We have the following entities and attributes:
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 41
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 42
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 43
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 44
Migration files
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 45
Create database & tables
1. rake db:create:all2. rake db:migrate
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 46
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 47
Adding Relationships
Notice: Songs is plural
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 48
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 49
Let’s begin
• Creating an instance of the Artist model. Type the following and hit enter.
jb = Artist.new(:name => 'Joe Bloggs' , :age => 22)
>> jb.age => 22 >> jb.id=> nil
>> jb.new_record?
=> true >> jb.name=> "Joe Bloggs“
Simple Query:
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 50
Learning more
>> jb.songs => []
Notice that the record gets an ID after it is saved:
>> jb.save=> true >> jb.id=> 1 Q: Why?
>> 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>
Save returns true on success.
Trying to save our song as this point gives us errors:>> tune.saveActiveRecord::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 51
Learning more
>> Genre.new(:name => 'Bluegrass').save=> true >> Genre.new(:name => 'Goa Trance').save => true >> Genre.new(:name => 'Doo Wop').save => true>> Genre.new(:name => 'Blues Rock').save=> true>> Genre.new(:name => 'Emo').save=> true
Let’s create some genres on the fly.
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 52
Learning more
>> tune .genre = Genre .find_by_name('Blues Rock')
• Assign the tune a genre:
>> tune.genre.name=> "Blues Rock“>> tune.genre_id => 4
• See that it has been set (don’t worry if your ID differs)
• Use the Array object’s << operand to append to Joe Blogg's song array and then save it.
>> jb.songs << tune>> tune.save=> true
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 53
Exploration>> jb.songs[0].title=> "Love Me Three Times">> tune.artist.name=> "Joe Bloggs">> tune.artist_id=> 1
>> bloggs = Artist.find_by_name('Joe Bloggs')
• Let’s fetch and create an instance of Joe Blogg’s record from the database
• Let’s explore this object further:
>> bloggs.name=> "Joe Bloggs">> bloggs.songs[0].title=> "Love Me Three Times">> bloggs.songs[0].genre.name=> "Blues Rock"
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 54
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 55
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 56
Change the default pageQ: Which file does this screen generate?
A: index.html
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
• 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 58
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 59
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 60
Task: Add a link to browse songs of the artist (cont.)
• Add a method (also called action) called “browse” in the artist controller
Answer: Step 2. Create an action in the controller
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 61
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 62
Result Screen
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 63
Backup
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 64
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 65
Screenshots
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 66
Screenshots (cont.) Relationship Highlight
229-511 Web Application Development Technology
Agile Programming, MVC Architecture & the practice with RoR 67
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 68
Screenshots (cont.) Export feature