The document summarizes various Active Record query interface features in Ruby on Rails, including:
1) Eager loading associations to reduce N+1 queries problems by including associated records in fewer queries.
2) Using scopes to define reusable Active Record relation queries and chain them for complex queries.
3) Finding records using dynamic finders like find_by and find_or_create to retrieve or initialize records matching attributes.
Slides from a presentation given at Laravel Chicago on November 18, 2014. Goes over the basics of building a REST API using the Laravel framework as well as some handy tips and tools.
Slides from a presentation given at Laravel Chicago on November 18, 2014. Goes over the basics of building a REST API using the Laravel framework as well as some handy tips and tools.
On February 18th, 2010 was O'Reilly's "Exploring Rails 3" online conference and these are Gregg Pollack's slides. They are by no means a complete record of improvements in Rails 3, but they should serve to get your appetite wet.
This talk describes refactoring FindBin::libs from Perl5 to Raku: breaking the module up into functional pieces, writing the tests using Raku, testing and releasing the module with mi6.
Rails and the Apache SOLR Search EngineDavid Keener
What good is content if nobody can find it? Many information sites are like icebergs, with only a limited amount of content directly accessible to users and the rest, the "underwater" potion, only available through searches. This talk shows how Rails web sites can take advantage of the world-class Apache SOLR search engine to provide sophisticated and customizable search features. We'll cover how to get started with SOLR, integrating with SOLR using the Sunspot gem, indexing, hit highlighting and other topics.
Laravel is a PHP MVC based framework. It is as easy as codeigniter, yet provides powerful tools needed for large robust application.It is built on top of symphony components and is inspired by many other frameworks including RoR, Asp .net, Sinatra.This session focuses on the basics things needed to start building application on it.
Les slides du Tools in Action que j'ai donné à Devoxx France 2019.
Le JDK est open source et son développement aussi. L'ensemble des nouveautés vit sur des branches Mercurial qui peuvent être téléchargées et compilées à la demande. Cela permet de jouer avec des fonctionnalités encore en chantier, de regarder comment les nouvelles syntaxes fonctionneront, bref, de jouer avec un JDK du futur, qui n'existera peut-être jamais. L'objet de ce tools in action est simple : montrer comment tout ceci fonctionne, de l'installation d'une machine Ubuntu à l'exécution d'un JDK recompilé maison.
Perl6 regular expression ("regex") syntax has a number of improvements over the Perl5 syntax. The inclusion of grammars as first-class entities in the language makes many uses of regexes clearer, simpler, and more maintainable. This talk looks at a few improvements in the regex syntax and also at how grammars can help make regex use cleaner and simpler.
There's been a lot of movement in the Java EE world. From the release of its 8th edition to the shift to Eclipse Foundation and recent rebranding to Jakarta EE. At the same time Eclipse MicroProfile shown up on the EE scene with the primary goal of evolving the spec towards microservice architectures.
With all these changes happening rapidly what has happened to Arquillian, the de-facto testing tool for Java EE applications?
Come to this session, you are going to explore the new and noteworthy of the Arquillian constellation. How standard Arquillian tests has been simplified as well as how microservice architecture has impacted on Arquillian offering integrations for polyglot persistence tests, contract testing or deployment tests for Docker, Kubernetes, and Openshift.
You'll learn that Arquillian is not only for Java EE.
On February 18th, 2010 was O'Reilly's "Exploring Rails 3" online conference and these are Gregg Pollack's slides. They are by no means a complete record of improvements in Rails 3, but they should serve to get your appetite wet.
This talk describes refactoring FindBin::libs from Perl5 to Raku: breaking the module up into functional pieces, writing the tests using Raku, testing and releasing the module with mi6.
Rails and the Apache SOLR Search EngineDavid Keener
What good is content if nobody can find it? Many information sites are like icebergs, with only a limited amount of content directly accessible to users and the rest, the "underwater" potion, only available through searches. This talk shows how Rails web sites can take advantage of the world-class Apache SOLR search engine to provide sophisticated and customizable search features. We'll cover how to get started with SOLR, integrating with SOLR using the Sunspot gem, indexing, hit highlighting and other topics.
Laravel is a PHP MVC based framework. It is as easy as codeigniter, yet provides powerful tools needed for large robust application.It is built on top of symphony components and is inspired by many other frameworks including RoR, Asp .net, Sinatra.This session focuses on the basics things needed to start building application on it.
Les slides du Tools in Action que j'ai donné à Devoxx France 2019.
Le JDK est open source et son développement aussi. L'ensemble des nouveautés vit sur des branches Mercurial qui peuvent être téléchargées et compilées à la demande. Cela permet de jouer avec des fonctionnalités encore en chantier, de regarder comment les nouvelles syntaxes fonctionneront, bref, de jouer avec un JDK du futur, qui n'existera peut-être jamais. L'objet de ce tools in action est simple : montrer comment tout ceci fonctionne, de l'installation d'une machine Ubuntu à l'exécution d'un JDK recompilé maison.
Perl6 regular expression ("regex") syntax has a number of improvements over the Perl5 syntax. The inclusion of grammars as first-class entities in the language makes many uses of regexes clearer, simpler, and more maintainable. This talk looks at a few improvements in the regex syntax and also at how grammars can help make regex use cleaner and simpler.
There's been a lot of movement in the Java EE world. From the release of its 8th edition to the shift to Eclipse Foundation and recent rebranding to Jakarta EE. At the same time Eclipse MicroProfile shown up on the EE scene with the primary goal of evolving the spec towards microservice architectures.
With all these changes happening rapidly what has happened to Arquillian, the de-facto testing tool for Java EE applications?
Come to this session, you are going to explore the new and noteworthy of the Arquillian constellation. How standard Arquillian tests has been simplified as well as how microservice architecture has impacted on Arquillian offering integrations for polyglot persistence tests, contract testing or deployment tests for Docker, Kubernetes, and Openshift.
You'll learn that Arquillian is not only for Java EE.
Roundup of what is on the web at regarding Rails 3 as of Easter 2010.
Includes outline of significant changes to Rais in Rails 3 plus how you might set about upgrading an existing app.
Acknowledges and links to to some amazing resources already elsewhere on the web.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
4. Bi-directional Associations
:inverse_of
class Customer < ActiveRecord::Base
has_many :orders, :inverse_of => :customer
end
class Order < ActiveRecord::Base
belongs_to :customer, :inverse_of => :orders
end
---------------------------------------------------
c = Customer.first
o = c.orders.first
c.first_name == o.customer.first_name # => true
c.first_name = 'Manny'
c.first_name == o.customer.first_name # => true
ROR Lab.
5. Overriding
Conditions
- reorder -
class Post < ActiveRecord::Base
..
..
has_many :comments, :order => 'posted_at DESC'
end
SELECT * FROM posts WHERE id = 10 ORDER BY name
SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC
ROR Lab.
6. Locking Records
for Update
• To prevent “race conditions”
• To ensure “atomic updates”
• Two locking mechanisms
‣ Optimistic Locking : version control
‣ Pessimistic Locking : DB lock
ROR Lab.
7. Optimistic Locking
• “lock_version” in DB table (default to 0)
• set_locking_column to change column name
c1 = Client.find(1)
c2 = Client.find(1)
c1.first_name = "Michael"
c1.save # increments the lock_version column
c2.name = "should fail"
ROR Lab.
8. Joining Tables
- Using Array/Hash of Named Associations -
only with INNER JOIN
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base • Multiple Associations
belongs_to :category
has_many :comments
has_many :tags
end Post.joins(:category, :comments)
class Comment < ActiveRecord::Base
belongs_to :post
has_one :guest SELECT posts.* FROM posts
end
INNER JOIN categories
class Guest < ActiveRecord::Base ON posts.category_id = categories.id
belongs_to :comment INNER JOIN comments
end ON comments.post_id = posts.id
class Tag < ActiveRecord::Base “return all posts that have a category and at least one comment”
belongs_to :post
end
ROR Lab.
9. Joining Tables
- Using Array/Hash of Named Associations -
only with INNER JOIN
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base • Nested Associations(Single Level)
belongs_to :category
has_many :comments
has_many :tags
end Post.joins(:comments => :guest)
class Comment < ActiveRecord::Base
belongs_to :post
has_one :guest SELECT posts.* FROM posts
end
INNER JOIN comments
class Guest < ActiveRecord::Base ON comments.post_id = posts.id
belongs_to :comment INNER JOIN guests
end ON guests.comment_id = comments.id
class Tag < ActiveRecord::Base
belongs_to :post
“return all posts that have a comment made by a guest”
end
ROR Lab.
11. Eager Loading
Associations
: as few queries as possible
N + 1 queries problem
clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
ROR Lab.
12. Eager Loading
Associations
: as few queries as possible
Solution to N + 1 queries problem Only 2 queries
clients = Client.includes(:address).limit(10)
clients.each do |client|
puts client.address.postcode
SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
ROR Lab.
14. Eager Loading
Associations
- Conditions on Eager Loaded Associations -
conditional “joins” > conditional “includes”
Post.includes(:comments)
.where("comments.visible", true)
SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5
FROM "posts"
LEFT OUTER JOIN "comments"
ON "comments"."post_id" = "posts"."id"
WHERE (comments.visible = 1)
ROR Lab.
15. Eager Loading
Associations
- Conditions on Eager Loaded Associations -
INNER JOIN LEFT OUTER JOIN
conditional “joins” > conditional “includes”
Post.includes(:comments)
.where("comments.visible", true)
SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5
FROM "posts"
LEFT OUTER JOIN "comments"
ON "comments"."post_id" = "posts"."id"
WHERE (comments.visible = 1)
ROR Lab.
16. Scopes
• To specify ARel queries
• Referenced as method calls on the
association objects or model
• finder methods in a scope
• return an ActiveRecord::Relation object
ROR Lab.
17. Scopes
class Post < ActiveRecord::Base
scope :published, where(:published => true)
end
ARel query
ROR Lab.
18. Scopes
chainable
class Post < ActiveRecord::Base
scope :published,
where(:published => true).joins(:category)
end
chainable within scopes
class Post < ActiveRecord::Base
scope :published, where(:published => true)
scope :published_and_commented,
published.and(self.arel_table[:comments_count].gt(0))
ROR Lab.
19. Scopes
To call the scope
Post.published # => [published posts]
category = Category.first
category.posts.published
# => [published posts belonging to this category]
ROR Lab.
20. Scopes
Working with times
class Post < ActiveRecord::Base
scope :last_week,
lambda { where("created_at < ?", Time.zone.now ) }
end a lambda so that the scope is evaluated every time
ROR Lab.
21. Scopes
Passing in arguments
class Post < ActiveRecord::Base
scope :1_week_before,
lambda { |time| where("created_at < ?", time) }
end
class Post < ActiveRecord::Base
def self.1_week_before(time)
where("created_at < ?", time)
end
***What about “as a class method” ?
ROR Lab.
22. Scopes
Passing in arguments
class Post < ActiveRecord::Base
scope :1_week_before,
lambda { |time| where("created_at < ?", time) }
end
le
eab
erclass Post < ActiveRecord::Base
ef
pr def self.1_week_before(time)
where("created_at < ?", time)
end
***What about “as a class method” ?
ROR Lab.
24. Scopes
Working with Scopes
client = Client.find_by_first_name("Ryan")
ROR Lab.
25. Scopes
Applying a default scope
class Client < ActiveRecord::Base
default_scope where("removed_at IS NULL")
SELECT * FROM clients WHERE removed_at IS NULL
ROR Lab.
26. Scopes
Removing all scopes
Especially useful,
when escaping the default_scope
ROR Lab.
28. Find or build
a new object
• first_or_create
• first_or_create! Exception on invalid
• first_or_initialize
ROR Lab.
29. Find or build
a new object
• first_or_create
Client.where(:first_name => 'Andy').first_or_create(:locked =>
false)
# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at:
"2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
Client.find_or_create_by_first_name(:first_name =>
"Andy", :locked => false)
SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
BEGIN
INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES
('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
COMMIT
ROR Lab.
30. Find or build
a new object
• first_or_create!
class Client < ActiveRecord::Base
validates :orders_count, :presence => true
end
Client.where(:first_name => 'Andy').first_or_create!(:locked =>
false)
# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
ROR Lab.
31. Find or build
a new object
• first_or_initialize
nick = Client.where(:first_name =>
'Nick').first_or_initialize(:locked => false)
# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: false,
created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
nick.persisted?
# => false
nick.new_record?
# => true
nick.save
# => true
persisted? vs new_record? ROR Lab.
32. Finding by SQL
: return an array of objects
where each object indicates a record
Client.find_by_sql("SELECT * FROM clients
INNER JOIN orders ON clients.id = orders.client_id
cf. connection.select_all
an array of hash
ROR Lab.
33. select_all
: return an array of hash
where each hash indicates a record
Client.connection.select_all("SELECT * FROM clients WHERE id =
cf. find_by_sql -> instantiates objects
ROR Lab.
34. pluck
To query a single column from the underlying table of a model
To return an array of values
Client.where(:active => true).pluck(:id)
# SELECT id FROM clients WHERE active = 1
Client.uniq.pluck(:role)
Client.select(:id).map { |c| c.id }
Client.pluck(:id)
ROR Lab.
35. Existence of
Objects
Client.exists?(1)
Client.exists?(1,2,3)
# or
Client.exists?([1,2,3])
Client.where(:first_name => 'Ryan').exists?
cf. find method
ROR Lab.
36. Existence of
Objects
# via a model
Post.any?
Post.many?
# via a named scope
Post.recent.any?
Post.recent.many?
# via a relation
Post.where(:published => true).any?
Post.where(:published => true).many?
# via an association
Post.first.categories.any?
ROR Lab.
37. Calculations
Client.count
# SELECT count(*) AS count_all FROM clients
Client.where(:first_name => 'Ryan').count
# SELECT count(*) AS count_all FROM clients WHERE (first_name =
'Ryan')
Client.includes("orders").where(:first_name => 'Ryan', :orders
SELECT count(DISTINCT clients.id) AS count_all FROM clients
LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
(clients.first_name = 'Ryan' AND orders.status = 'received')
ROR Lab.
39. Running EXPLAIN
a pretty printing that emulates the one of the database shells
User.where(:id => 1).joins(:posts).explain
EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id`
=1
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
2 rows in set (0.00 sec)
under MySQL
ROR Lab.
40. Running EXPLAIN
a pretty printing that emulates the one of the database shells
User.where(:id => 1).joins(:posts).explain
EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "users"."id" = 1
QUERY PLAN
------------------------------------------------------------------------------
Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
Join Filter: (posts.user_id = users.id)
-> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
Index Cond: (id = 1)
-> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
Filter: (posts.user_id = 1)
(6 rows)
under PostgreSQL
ROR Lab.
41. Running EXPLAIN
Eager Loading
User.where(:id => 1).includes(:posts).explain
EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
+----+-------------+-------+------+---------------+------+---------+------+------+-------------
+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------
+
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
under MySQL ROR Lab.
42. Running EXPLAIN
Automatic EXPLAIN
To set the threshold in seconds
config.active_record.auto_explain_threshold_in_seconds
• disables automatic EXPLAIN => nil or no AR logger
• Development mode => default, 0.5 sec
• Test mode => nil
• Production mode => nil
ROR Lab.
43. Running EXPLAIN
Disabling Automatic EXPLAIN
To be selectively silenced with
ActiveRecord::Base.silence_auto_explain do
# no automatic EXPLAIN is triggered here
• useful for queries are slow but fine
: a heavyweight report of a admin interface
ROR Lab.