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?
Ad

More Related Content

What's hot (20)

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
 
Asp objects
Asp objectsAsp objects
Asp objects
Kavya Bhaisora
 
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
AoteaStudios
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Venkat Pinagadi
 
Cassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesCassandra rapid prototyping with achilles
Cassandra rapid prototyping with achilles
Duyhai Doan
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laid
Swizec 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
Ajax
Sanoj Kumar
 
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
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
JayaPrakash.m
 
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
 
Kubernetes Operators With Scala
Kubernetes Operators With ScalaKubernetes Operators With Scala
Kubernetes Operators With Scala
Peter Barron
 
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 developers
AoteaStudios
 
Cassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesCassandra rapid prototyping with achilles
Cassandra rapid prototyping with achilles
Duyhai Doan
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laid
Swizec 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
 
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
 
Kubernetes Operators With Scala
Kubernetes Operators With ScalaKubernetes Operators With Scala
Kubernetes Operators With Scala
Peter Barron
 

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
safa-medaney
 
Leading Minds report
Leading Minds reportLeading Minds report
Leading Minds report
Danny VandeVyver
 
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
 
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Изкуството на Удовлетворението. Кариера и Мисия в Свобода.
Виржиния Тинчева
 
Infor
InforInfor
Infor
xabier1
 
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 Presentation
Hamed 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
 
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 Presentation
Hamed 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
 
Німецька мова. 4 клас. Практичне заняття на тему «Свята». Молодша школа (на...
Німецька мова. 4 клас.   Практичне заняття на тему «Свята». Молодша школа (на...Німецька мова. 4 клас.   Практичне заняття на тему «Свята». Молодша школа (на...
Німецька мова. 4 клас. Практичне заняття на тему «Свята». Молодша школа (на...
Електронні книги Ранок
 
Ad

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
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
 
Android Database
Android DatabaseAndroid Database
Android Database
Rashad Aliyev
 
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
Raimonds Simanovskis
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
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
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
Guacamole
ArangoDB Database
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
info_zybotech
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
James Johnson
 
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
 
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
 
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 Oracle
Raimonds Simanovskis
 
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 .
 
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
 
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
 
Ad

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
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
Rspec Tweaks
Ombu Labs, The Lean Software Boutique
 
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
CSS3 Animations
Ombu Labs, The Lean Software Boutique
 
Git Sensitive Data
Git Sensitive DataGit Sensitive Data
Git Sensitive Data
Ombu Labs, The Lean Software Boutique
 
Bitpagos Ruby Gem
Bitpagos Ruby GemBitpagos Ruby Gem
Bitpagos Ruby Gem
Ombu Labs, The Lean Software Boutique
 
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
Mocks vs. Stubs
Ombu Labs, The Lean Software Boutique
 
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
Peer Review Guidelines
Ombu Labs, The Lean Software Boutique
 
Recycling at Ombu Labs
Recycling at Ombu LabsRecycling at Ombu Labs
Recycling at Ombu Labs
Ombu Labs, The Lean Software Boutique
 
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
 

Recently uploaded (20)

Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 

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: “[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]’)
  • 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: “[email protected]”>
  • 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: “[email protected]”> > User.not_real.where(id: 2) => []