11
An Introduction to ActiveRecord OmbuLabs, August 2015

Intro to Active Record

Embed Size (px)

Citation preview

Page 1: Intro to Active Record

An Introduction to ActiveRecord

OmbuLabs, August 2015

Page 2: Intro to Active Record

Active Record is a design pattern

“An object that wraps a row in a database table, encapsulates the database access,

and adds domain logic on that data.”

http://www.martinfowler.com/eaaCatalog/activeRecord.html

Page 3: Intro to Active Record

One class per table (usually)

Rails Modelclass User < ActiveRecord::Baseend

DatabaseCREATE TABLE `users` ( `id` int(11) NOT NULL auto_increment, `login` varchar(255), `email` varchar(255), `updated_at` datetime default NULL, `created_at` datetime default NULL, PRIMARY KEY (`id`))

Page 4: Intro to Active Record

One object per table row

Page 5: Intro to Active Record

One attribute per table column

Page 6: Intro to Active Record

The ActiveRecord we know

app/models/user.rbclass User < ActiveRecord::Baseend

Creating a user> user = User.new(email: “[email protected]”)# the user doesn’t exist in our database yet. ALL Ruby classes have the `new` method. > user.save! SQL (14.1ms) INSERT INTO `users` (`email`) VALUES (‘[email protected]’)# user is now saved to the database.

> User.create(email: “[email protected]”)SQL (14.1ms) INSERT INTO `users` (`email`) VALUES (‘[email protected]’)

Page 7: Intro to Active Record

The ActiveRecord we know

app/models/user.rbclass User < ActiveRecord::Baseend

Loading a user> user = User.find(1)User load (0.00514) SELECT * FROM users WHERE (users.id = 1) LIMIT 1=> #<User id: 1, email: “[email protected]”>

Page 8: Intro to Active Record

Associations1 to 1 has_one & belongs_to

1 to n has_many & belongs_to

n to n has_and_belongs_to_many has_many :through

Page 9: Intro to Active Record

What can AR return?

ActiveRecord can return a single object, an array of objects, or an Active Relation, among others.

User.find(1) => # Single objectUser.first => # Single objectUser.last => # Single objectUser.all => # Array of objectsUser.count => # IntegerUser.where(id: 1) => # Active Relation

Page 10: Intro to Active Record

Active Relations & Scopes

You can chain conditions before hitting the database by using `joins`, `where`, `order` and scopes. class User < ActiveRecord::Base scope :not_real, -> { where(“email like ?”, “%example.com%”) }end

> User.not_real=> #<User id: 1, email: “[email protected]”>

> User.not_real.where(id: 2)=> []

Page 11: Intro to Active Record

THANK YOU!questions?