Agile Data Science by Russell Jurney_ The Hive_Janruary 29 2014
Active Record PowerPoint
1. What in the world is
ActiveRecord?
A: (sweet ruby) MAGIC in the form of a Design Pattern!
2. Let’s start with SQL!
Wait what? That’s not ActiveRecord
• SQL stands for Structured Query Language
• There are a ton of different SQL Databases!!
3. • SQL lets you manage data in a relational database
• Insert - Create a new row of information in a table
• Update - Change information in an existing row
• Select - Retrieve information in a table
• Delete - Remove a row in a table
• SQL uses data types such as String, Text, Integer,
Date, Time
• An SQL query looks like this:
SELECT * FROM cats WHERE cats.breed = ‘Sphynx’;
How does SQL even…?
4. Doing it the Ruby Way
Active Record Pattern
Convention over Configuration (CoC)
Don’t Repeat Yourself (DRY)
Model-View-Controller (MVC)
• Some Frameworks require you to write a lot of
configuration code.
• Rails Adopts Conventions so you don’t have to!
1. Naming Conventions
2. Schema Conventions
3. Query Interface
Ruby on Rails Guides: http://guides.rubyonrails.org/active_record_basics.html#convention-over-configuration-in-active-record
5. What’s an ORM?
• ORM stands for Object Relational Mapper
• Maps database to ruby object
• They get rid of SQL queries in code
SELECT * FROM cats VS Cats.all
• Essentially ActiveRecord takes ruby code and translates
it into SQL code.
Hint: Active Record is Ruby’s way of dealing with ugly SQL!
6. Active Record is the “M” in MVC
model: DOGGIE
id name color spotted adorable age
1 Chowderhead tan and white FALSE TRUE 1
2 Paco snow white FALSE TRUE 3
3 Tenley brown and
white spots
TRUE TRUE 5
Models are Ruby classes.
• They talk to the database
• Store and validate data
• Performs the logic of knowing
about an instance of itself
So… what is a MODEL anyway??
7. Active Record Relationships
How Do Models Connect with Each Other?
Lets start easy:
A Supplier has one Account
(This is a One-to-One Relationship)
9. And when a Doctor has many Patients,
but a Patient has many Doctors too!
…and they both have many Appointments!
10. So Why Associations?
• Make ugly SQL statements Ruby-Friendly:
SELECT surveys FROM surveys JOIN ON users WHERE user.name LIKE “Dicko”
—becomes—
dicko = User.find_by_name(“Dicko”)
dicko.surveys
• We are basically making wonderful Ruby Methods with
each association we declare!
• Remember: IT ONLY LOOKS LIKE MAGIC (it never is)