View
252
Download
0
Embed Size (px)
Citation preview
An Introduction to ActiveRecord
OmbuLabs, August 2015
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
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`))
One object per table row
One attribute per table column
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]’)
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]”>
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
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
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)=> []
THANK YOU!questions?