active record powerpoint
TRANSCRIPT
What in the world is ActiveRecord?
A: (sweet ruby) MAGIC in the form of a Design Pattern!
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!!
• 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…?
Doing it the Ruby Way
Active Record PatternConvention 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 Conventions2. Schema Conventions3. Query Interface
Ruby on Rails Guides: http://guides.rubyonrails.org/active_record_basics.html#convention-over-configuration-in-active-record
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!
Active Record is the “M” in MVC
model: DOGGIEid 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??
Active Record RelationshipsHow Do Models Connect with Each Other?
Lets start easy:A Supplier has one Account
(This is a One-to-One Relationship)
Alternately,an Order belongs to a Customer
(Also, a One-to-One Relationship)
More Active Record Relationships
And when a Doctor has many Patients,but a Patient has many Doctors too!
…and they both have many Appointments!
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)