Rails uses an object-relational mapping (ORM) approach to work with databases. Model classes represent tables in the database and are mapped to rows. Migrations are used to initialize the database structure, and models then allow objects to perform CRUD operations on rows through Active Record. This allows Rails to interact with all major SQL databases using an object-oriented interface.
6. Database (DB): Organized collection of data
Database Management System (DBMS):
Controls the creation, maintenance, and
use of a DB
Examples:
PostgreSQL
10. Two key aspects of a DBMS
• Database model: How DB is structured and used
– Examples: Relational, Object-Oriented, Hierarchical
• Query language: Types of questions you can ask
– Examples: SQL, XQuery
Relational model + SQL is most common
and used by Rails
12. Example Tables
id first_name last_name year_born
1 Ayn Rand 1905
2 Peter Benchley 1940
id publisher_name
1 Bobbs Merrill
2 Random House
authors
publishers
13. How Apps Use DBs
• Pre-deployment of app:
– Create (empty) tables
• Rails migrations do this
– Maybe “seed” with data
• At runtime of app:
– CRUD table rows
• Rails model classes do this
• NOTE: Tables/columns don’t change
15. Example SELECT Queries
• SELECT * FROM authors
• SELECT * FROM authors WHERE year_born > 1910
• SELECT * FROM authors WHERE last_name REGEXP '[a-r]*'
• SELECT * FROM authors WHERE last_name REGEXP '[a-r]*'
ORDER BY last_name ASC
For complete MySQL documentation, see http://dev.mysql.com/doc/refman/5.5/en/select.html,
http://dev.mysql.com/doc/refman/5.5/en/pattern-matching.html
id first_name last_name year_born
1 Ayn Rand 1905
2 Peter Benchley 1940
authors
18. Quick Intro to UML Class Diagrams
• I use UML class diagrams a lot
• Rationale: Easier to see “big picture” relationships
than in code
• Example model class:
first_name : string
last_name : string
year_born : integer
Author
Box = class
Class name
Attributes w/ types
20. Example Mapping from Class to Table
id first_name last_name year_born
1 Ayn Rand 1905
2 Peter Benchley 1940
authors
first_name : string
last_name : string
year_born : integer
Author
You get ID
for free
23. id first_name last_name year_born
1 Ayn Rand 1905
2 Peter Benchley 1940
authors
first_name : string
last_name : string
year_born : integer
Author
Model
DB
Migrations
See the Demos-n-Deets for
How This ORM Is Applied in
Rails Model Programming
24. Summary
• Rails Model Components
• DBs and DBMSs
• Rails DB Migrations
• Rails ORM
http://flic.kr/p/aCLor3