SlideShare a Scribd company logo
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 Model
class User < ActiveRecord::Base
end
Database
CREATE 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.rb
class User < ActiveRecord::Base
end
Creating a user
> user = User.new(email: “example@example.com”)
# 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
(‘example@example.com’)
# user is now saved to the database.
> User.create(email: “example@example.com”)
SQL (14.1ms) INSERT INTO `users` (`email`) VALUES
(‘example@example.com’)
The ActiveRecord we know
app/models/user.rb
class User < ActiveRecord::Base
end
Loading a user
> user = User.find(1)
User load (0.00514) SELECT * FROM users WHERE
(users.id = 1) LIMIT 1
=> #<User id: 1, email: “example@example.com”>
Associations
1 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 object
User.first => # Single object
User.last => # Single object
User.all => # Array of objects
User.count => # Integer
User.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: “example@example.com”>
> User.not_real.where(id: 2)
=> []
THANK YOU!
questions?

More Related Content

What's hot

Effective cassandra development with achilles
Effective cassandra development with achillesEffective cassandra development with achilles
Effective cassandra development with achilles
Duyhai Doan
 
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
Sonja Madsen
 
iOS Beginners Lesson 1
iOS Beginners Lesson 1iOS Beginners Lesson 1
iOS Beginners Lesson 1
Calvin Cheng
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersAoteaStudios
 
Cassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesCassandra rapid prototyping with achilles
Cassandra rapid prototyping with achilles
Duyhai Doan
 
Ajax
AjaxAjax
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laidSwizec Teller
 
Slick – the modern way to access your Data
Slick – the modern way to access your DataSlick – the modern way to access your Data
Slick – the modern way to access your Data
Jochen Huelss
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Shakir Majeed Khan
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
Ajax
AjaxAjax
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
Akshay Mathur
 
Single page application 07
Single page application   07Single page application   07
Single page application 07
Ismaeel Enjreny
 
Cache, Workers, and Queues
Cache, Workers, and QueuesCache, Workers, and Queues
Cache, Workers, and Queues
Jason McCreary
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
Ivano Malavolta
 

What's hot (20)

Effective cassandra development with achilles
Effective cassandra development with achillesEffective cassandra development with achilles
Effective cassandra development with achilles
 
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
 
iOS Beginners Lesson 1
iOS Beginners Lesson 1iOS Beginners Lesson 1
iOS Beginners Lesson 1
 
Asp objects
Asp objectsAsp objects
Asp objects
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Cassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesCassandra rapid prototyping with achilles
Cassandra rapid prototyping with achilles
 
Ajax
AjaxAjax
Ajax
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laid
 
Slick – the modern way to access your Data
Slick – the modern way to access your DataSlick – the modern way to access your Data
Slick – the modern way to access your Data
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Ajax
AjaxAjax
Ajax
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
 
Single page application 07
Single page application   07Single page application   07
Single page application 07
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
Cache, Workers, and Queues
Cache, Workers, and QueuesCache, Workers, and Queues
Cache, Workers, and Queues
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
 

Viewers also liked

How do an organism’s trait help it survive
How do an organism’s trait help it surviveHow do an organism’s trait help it survive
How do an organism’s trait help it survive
safa-medaney
 
Presentación Exposición Guatemala - AECID - Febrero 2012
Presentación Exposición Guatemala - AECID - Febrero 2012Presentación Exposición Guatemala - AECID - Febrero 2012
Presentación Exposición Guatemala - AECID - Febrero 2012
Charo Moreno Galiano
 
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Виржиния Тинчева
 
tipos de prueba desarrollo software
tipos de prueba desarrollo softwaretipos de prueba desarrollo software
tipos de prueba desarrollo software
Home
 
HERRAMIENTAS DE ANÁLISIS DE DATOS
HERRAMIENTAS DE ANÁLISIS DE DATOSHERRAMIENTAS DE ANÁLISIS DE DATOS
HERRAMIENTAS DE ANÁLISIS DE DATOS
Home
 
Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.
Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.
Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.
Yasen Nikolov
 
Respostas colorindo o reino plantae
Respostas colorindo o reino plantaeRespostas colorindo o reino plantae
Respostas colorindo o reino plantae
Simone Miranda
 
Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...
Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...
Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...
Yasen Nikolov
 
ACA Group Presentation
ACA Group PresentationACA Group Presentation
ACA Group PresentationHamed Jabbari
 
Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...
Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...
Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...
VMware Tanzu
 
Lambda Calculus
Lambda CalculusLambda Calculus
Lambda Calculus
K. N. Toosi University
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
Jyaasa Technologies
 
Frictional Force
Frictional ForceFrictional Force
Frictional Force
Shadiya Basheer
 
Німецька мова. 4 клас. Практичне заняття на тему «Свята». Молодша школа (на...
Німецька мова. 4 клас.   Практичне заняття на тему «Свята». Молодша школа (на...Німецька мова. 4 клас.   Практичне заняття на тему «Свята». Молодша школа (на...
Німецька мова. 4 клас. Практичне заняття на тему «Свята». Молодша школа (на...
Електронні книги Ранок
 
Methods of Irrigation
Methods of IrrigationMethods of Irrigation
Methods of Irrigation
Latif Hyder Wadho
 

Viewers also liked (17)

How do an organism’s trait help it survive
How do an organism’s trait help it surviveHow do an organism’s trait help it survive
How do an organism’s trait help it survive
 
Leading Minds report
Leading Minds reportLeading Minds report
Leading Minds report
 
Presentación Exposición Guatemala - AECID - Febrero 2012
Presentación Exposición Guatemala - AECID - Febrero 2012Presentación Exposición Guatemala - AECID - Febrero 2012
Presentación Exposición Guatemala - AECID - Febrero 2012
 
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
 
Infor
InforInfor
Infor
 
tipos de prueba desarrollo software
tipos de prueba desarrollo softwaretipos de prueba desarrollo software
tipos de prueba desarrollo software
 
HERRAMIENTAS DE ANÁLISIS DE DATOS
HERRAMIENTAS DE ANÁLISIS DE DATOSHERRAMIENTAS DE ANÁLISIS DE DATOS
HERRAMIENTAS DE ANÁLISIS DE DATOS
 
Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.
Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.
Как да станем най-търсените и добри приятели! Сила за Успех с Ясен Николов.
 
Respostas colorindo o reino plantae
Respostas colorindo o reino plantaeRespostas colorindo o reino plantae
Respostas colorindo o reino plantae
 
Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...
Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...
Как да се свързваме с другите и да създаваме приятелства. Сила за комуникация...
 
ACA Group Presentation
ACA Group PresentationACA Group Presentation
ACA Group Presentation
 
Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...
Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...
Achieving Mega-Scale Business Intelligence Through Speed of Thought Analytics...
 
Lambda Calculus
Lambda CalculusLambda Calculus
Lambda Calculus
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Frictional Force
Frictional ForceFrictional Force
Frictional Force
 
Німецька мова. 4 клас. Практичне заняття на тему «Свята». Молодша школа (на...
Німецька мова. 4 клас.   Практичне заняття на тему «Свята». Молодша школа (на...Німецька мова. 4 клас.   Практичне заняття на тему «Свята». Молодша школа (на...
Німецька мова. 4 клас. Практичне заняття на тему «Свята». Молодша школа (на...
 
Methods of Irrigation
Methods of IrrigationMethods of Irrigation
Methods of Irrigation
 

Similar to Intro to Active Record

Ruby on Rails For .Net Programmers
Ruby on Rails For .Net ProgrammersRuby on Rails For .Net Programmers
Ruby on Rails For .Net Programmers
daveverwer
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on Rails
Raimonds Simanovskis
 
Local Storage
Local StorageLocal Storage
Local Storage
Ivano Malavolta
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
Balint Erdi
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
Khaled Anaqwa
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Rabble .
 
Sq lite database
Sq lite databaseSq lite database
Sq lite database
AYESHA JAVED
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
Rabble .
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
Getting Started with Rails
Getting Started with RailsGetting Started with Rails
Getting Started with Rails
Basayel Said
 
とりあえず使うScalaz
とりあえず使うScalazとりあえず使うScalaz
とりあえず使うScalaz
Shuya Tsukamoto
 
Guacamole
GuacamoleGuacamole
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
info_zybotech
 
Rajab Davudov - Android Database
Rajab Davudov - Android DatabaseRajab Davudov - Android Database
Rajab Davudov - Android Database
Rashad Aliyev
 
Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android
yugandhar vadlamudi
 

Similar to Intro to Active Record (20)

Ruby on Rails For .Net Programmers
Ruby on Rails For .Net ProgrammersRuby on Rails For .Net Programmers
Ruby on Rails For .Net Programmers
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on Rails
 
Local Storage
Local StorageLocal Storage
Local Storage
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
Android Database
Android DatabaseAndroid Database
Android Database
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Scala active record
Scala active recordScala active record
Scala active record
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
Sq lite database
Sq lite databaseSq lite database
Sq lite database
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Getting Started with Rails
Getting Started with RailsGetting Started with Rails
Getting Started with Rails
 
とりあえず使うScalaz
とりあえず使うScalazとりあえず使うScalaz
とりあえず使うScalaz
 
Guacamole
GuacamoleGuacamole
Guacamole
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Rajab Davudov - Android Database
Rajab Davudov - Android DatabaseRajab Davudov - Android Database
Rajab Davudov - Android Database
 
Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android
 

More from Ombu Labs, The Lean Software Boutique

Trabajando en Código Abierto
Trabajando en Código AbiertoTrabajando en Código Abierto
Trabajando en Código Abierto
Ombu Labs, The Lean Software Boutique
 
Design Patterns: Strategy and NullObject
Design Patterns: Strategy and NullObjectDesign Patterns: Strategy and NullObject
Design Patterns: Strategy and NullObject
Ombu Labs, The Lean Software Boutique
 
Our Values at The Lean Software Boutique
Our Values at The Lean Software BoutiqueOur Values at The Lean Software Boutique
Our Values at The Lean Software Boutique
Ombu Labs, The Lean Software Boutique
 
Rspec Tweaks
Rspec TweaksRspec Tweaks
A short guide to git's interactive rebase
A short guide to git's interactive rebaseA short guide to git's interactive rebase
A short guide to git's interactive rebase
Ombu Labs, The Lean Software Boutique
 
CSS3 Animations
CSS3 AnimationsCSS3 Animations
Git Sensitive Data
Git Sensitive DataGit Sensitive Data
Bitpagos Ruby Gem
Bitpagos Ruby GemBitpagos Ruby Gem
Open Source Recap (Dec '15) by etagwerker
Open Source Recap (Dec '15) by etagwerkerOpen Source Recap (Dec '15) by etagwerker
Open Source Recap (Dec '15) by etagwerker
Ombu Labs, The Lean Software Boutique
 
Gotchas and Stack Traces in Ruby
Gotchas and Stack Traces in RubyGotchas and Stack Traces in Ruby
Gotchas and Stack Traces in Ruby
Ombu Labs, The Lean Software Boutique
 
Mocks vs. Stubs
Mocks vs. StubsMocks vs. Stubs
Relational Databases 101
Relational Databases 101Relational Databases 101
Relational Databases 101
Ombu Labs, The Lean Software Boutique
 
The 7 Days Open Source Challenge
The 7 Days Open Source ChallengeThe 7 Days Open Source Challenge
The 7 Days Open Source Challenge
Ombu Labs, The Lean Software Boutique
 
Basic memoization in Ruby
Basic memoization in RubyBasic memoization in Ruby
Basic memoization in Ruby
Ombu Labs, The Lean Software Boutique
 
Productivity Tips for Programmers
Productivity Tips for ProgrammersProductivity Tips for Programmers
Productivity Tips for Programmers
Ombu Labs, The Lean Software Boutique
 
Testing 101: Three Rules for Testing at Ombu Labs
Testing 101: Three Rules for Testing at Ombu Labs Testing 101: Three Rules for Testing at Ombu Labs
Testing 101: Three Rules for Testing at Ombu Labs
Ombu Labs, The Lean Software Boutique
 
Peer Review Guidelines
Peer Review GuidelinesPeer Review Guidelines
Recycling at Ombu Labs
Recycling at Ombu LabsRecycling at Ombu Labs
Guide to Services & Technology at Ombu Labs
Guide to Services & Technology at Ombu LabsGuide to Services & Technology at Ombu Labs
Guide to Services & Technology at Ombu Labs
Ombu Labs, The Lean Software Boutique
 

More from Ombu Labs, The Lean Software Boutique (19)

Trabajando en Código Abierto
Trabajando en Código AbiertoTrabajando en Código Abierto
Trabajando en Código Abierto
 
Design Patterns: Strategy and NullObject
Design Patterns: Strategy and NullObjectDesign Patterns: Strategy and NullObject
Design Patterns: Strategy and NullObject
 
Our Values at The Lean Software Boutique
Our Values at The Lean Software BoutiqueOur Values at The Lean Software Boutique
Our Values at The Lean Software Boutique
 
Rspec Tweaks
Rspec TweaksRspec Tweaks
Rspec Tweaks
 
A short guide to git's interactive rebase
A short guide to git's interactive rebaseA short guide to git's interactive rebase
A short guide to git's interactive rebase
 
CSS3 Animations
CSS3 AnimationsCSS3 Animations
CSS3 Animations
 
Git Sensitive Data
Git Sensitive DataGit Sensitive Data
Git Sensitive Data
 
Bitpagos Ruby Gem
Bitpagos Ruby GemBitpagos Ruby Gem
Bitpagos Ruby Gem
 
Open Source Recap (Dec '15) by etagwerker
Open Source Recap (Dec '15) by etagwerkerOpen Source Recap (Dec '15) by etagwerker
Open Source Recap (Dec '15) by etagwerker
 
Gotchas and Stack Traces in Ruby
Gotchas and Stack Traces in RubyGotchas and Stack Traces in Ruby
Gotchas and Stack Traces in Ruby
 
Mocks vs. Stubs
Mocks vs. StubsMocks vs. Stubs
Mocks vs. Stubs
 
Relational Databases 101
Relational Databases 101Relational Databases 101
Relational Databases 101
 
The 7 Days Open Source Challenge
The 7 Days Open Source ChallengeThe 7 Days Open Source Challenge
The 7 Days Open Source Challenge
 
Basic memoization in Ruby
Basic memoization in RubyBasic memoization in Ruby
Basic memoization in Ruby
 
Productivity Tips for Programmers
Productivity Tips for ProgrammersProductivity Tips for Programmers
Productivity Tips for Programmers
 
Testing 101: Three Rules for Testing at Ombu Labs
Testing 101: Three Rules for Testing at Ombu Labs Testing 101: Three Rules for Testing at Ombu Labs
Testing 101: Three Rules for Testing at Ombu Labs
 
Peer Review Guidelines
Peer Review GuidelinesPeer Review Guidelines
Peer Review Guidelines
 
Recycling at Ombu Labs
Recycling at Ombu LabsRecycling at Ombu Labs
Recycling at Ombu Labs
 
Guide to Services & Technology at Ombu Labs
Guide to Services & Technology at Ombu LabsGuide to Services & Technology at Ombu Labs
Guide to Services & Technology at Ombu Labs
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 

Intro to Active Record

  • 2. 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
  • 3. One class per table (usually) Rails Model class User < ActiveRecord::Base end Database CREATE 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`) )
  • 4. One object per table row
  • 5. One attribute per table column
  • 6. The ActiveRecord we know app/models/user.rb class User < ActiveRecord::Base end Creating a user > user = User.new(email: “example@example.com”) # 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 (‘example@example.com’) # user is now saved to the database. > User.create(email: “example@example.com”) SQL (14.1ms) INSERT INTO `users` (`email`) VALUES (‘example@example.com’)
  • 7. The ActiveRecord we know app/models/user.rb class User < ActiveRecord::Base end Loading a user > user = User.find(1) User load (0.00514) SELECT * FROM users WHERE (users.id = 1) LIMIT 1 => #<User id: 1, email: “example@example.com”>
  • 8. Associations 1 to 1 has_one & belongs_to 1 to n has_many & belongs_to n to n has_and_belongs_to_many has_many :through
  • 9. What can AR return? ActiveRecord can return a single object, an array of objects, or an Active Relation, among others. User.find(1) => # Single object User.first => # Single object User.last => # Single object User.all => # Array of objects User.count => # Integer User.where(id: 1) => # Active Relation
  • 10. 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: “example@example.com”> > User.not_real.where(id: 2) => []