rails 4.1.14.2 → 5.2.4.4
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- checksums.yaml +5 -5
- data/README.md +33 -19
- metadata +65 -313
- data/guides/CHANGELOG.md +0 -106
- data/guides/Rakefile +0 -77
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -53
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -710
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -53
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/code/getting_started/Gemfile +0 -40
- data/guides/code/getting_started/Gemfile.lock +0 -125
- data/guides/code/getting_started/README.rdoc +0 -28
- data/guides/code/getting_started/Rakefile +0 -6
- data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
- data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
- data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
- data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
- data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
- data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
- data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
- data/guides/code/getting_started/app/models/comment.rb +0 -3
- data/guides/code/getting_started/app/models/post.rb +0 -7
- data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
- data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
- data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
- data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
- data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
- data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
- data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
- data/guides/code/getting_started/bin/bundle +0 -4
- data/guides/code/getting_started/bin/rails +0 -4
- data/guides/code/getting_started/bin/rake +0 -4
- data/guides/code/getting_started/config.ru +0 -4
- data/guides/code/getting_started/config/application.rb +0 -18
- data/guides/code/getting_started/config/boot.rb +0 -4
- data/guides/code/getting_started/config/database.yml +0 -25
- data/guides/code/getting_started/config/environment.rb +0 -5
- data/guides/code/getting_started/config/environments/development.rb +0 -30
- data/guides/code/getting_started/config/environments/production.rb +0 -80
- data/guides/code/getting_started/config/environments/test.rb +0 -36
- data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
- data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
- data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
- data/guides/code/getting_started/config/initializers/locale.rb +0 -9
- data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
- data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
- data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
- data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
- data/guides/code/getting_started/config/locales/en.yml +0 -23
- data/guides/code/getting_started/config/routes.rb +0 -7
- data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
- data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
- data/guides/code/getting_started/db/schema.rb +0 -33
- data/guides/code/getting_started/db/seeds.rb +0 -7
- data/guides/code/getting_started/public/404.html +0 -60
- data/guides/code/getting_started/public/422.html +0 -60
- data/guides/code/getting_started/public/500.html +0 -59
- data/guides/code/getting_started/public/favicon.ico +0 -0
- data/guides/code/getting_started/public/robots.txt +0 -5
- data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
- data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
- data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
- data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
- data/guides/code/getting_started/test/models/comment_test.rb +0 -7
- data/guides/code/getting_started/test/models/post_test.rb +0 -7
- data/guides/code/getting_started/test/test_helper.rb +0 -12
- data/guides/rails_guides.rb +0 -63
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -31
- data/guides/rails_guides/markdown.rb +0 -163
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -556
- data/guides/source/3_2_release_notes.md +0 -565
- data/guides/source/4_0_release_notes.md +0 -276
- data/guides/source/4_1_release_notes.md +0 -731
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -25
- data/guides/source/action_controller_overview.md +0 -1175
- data/guides/source/action_mailer_basics.md +0 -689
- data/guides/source/action_view_overview.md +0 -1602
- data/guides/source/active_model_basics.md +0 -200
- data/guides/source/active_record_basics.md +0 -373
- data/guides/source/active_record_callbacks.md +0 -410
- data/guides/source/active_record_querying.md +0 -1785
- data/guides/source/active_record_validations.md +0 -1169
- data/guides/source/active_support_core_extensions.md +0 -3817
- data/guides/source/active_support_instrumentation.md +0 -496
- data/guides/source/api_documentation_guidelines.md +0 -315
- data/guides/source/asset_pipeline.md +0 -1165
- data/guides/source/association_basics.md +0 -2229
- data/guides/source/caching_with_rails.md +0 -354
- data/guides/source/command_line.md +0 -603
- data/guides/source/configuring.md +0 -942
- data/guides/source/contributing_to_ruby_on_rails.md +0 -544
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -707
- data/guides/source/development_dependencies_install.md +0 -278
- data/guides/source/documents.yaml +0 -193
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1001
- data/guides/source/generators.md +0 -663
- data/guides/source/getting_started.md +0 -1946
- data/guides/source/i18n.md +0 -1043
- data/guides/source/index.html.erb +0 -27
- data/guides/source/initialization.md +0 -657
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -146
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -75
- data/guides/source/migrations.md +0 -1143
- data/guides/source/nested_model_forms.md +0 -225
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -248
- data/guides/source/rails_on_rack.md +0 -332
- data/guides/source/routing.md +0 -1115
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
- data/guides/source/security.md +0 -1018
- data/guides/source/testing.md +0 -1052
- data/guides/source/upgrading_ruby_on_rails.md +0 -928
- data/guides/source/working_with_javascript_in_rails.md +0 -405
- data/guides/w3c_validator.rb +0 -95
@@ -1,410 +0,0 @@
|
|
1
|
-
Active Record Callbacks
|
2
|
-
=======================
|
3
|
-
|
4
|
-
This guide teaches you how to hook into the life cycle of your Active Record
|
5
|
-
objects.
|
6
|
-
|
7
|
-
After reading this guide, you will know:
|
8
|
-
|
9
|
-
* The life cycle of Active Record objects.
|
10
|
-
* How to create callback methods that respond to events in the object life cycle.
|
11
|
-
* How to create special classes that encapsulate common behavior for your callbacks.
|
12
|
-
|
13
|
-
--------------------------------------------------------------------------------
|
14
|
-
|
15
|
-
The Object Life Cycle
|
16
|
-
---------------------
|
17
|
-
|
18
|
-
During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.
|
19
|
-
|
20
|
-
Callbacks allow you to trigger logic before or after an alteration of an object's state.
|
21
|
-
|
22
|
-
Callbacks Overview
|
23
|
-
------------------
|
24
|
-
|
25
|
-
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
|
26
|
-
|
27
|
-
### Callback Registration
|
28
|
-
|
29
|
-
In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
|
30
|
-
|
31
|
-
```ruby
|
32
|
-
class User < ActiveRecord::Base
|
33
|
-
validates :login, :email, presence: true
|
34
|
-
|
35
|
-
before_validation :ensure_login_has_a_value
|
36
|
-
|
37
|
-
protected
|
38
|
-
def ensure_login_has_a_value
|
39
|
-
if login.nil?
|
40
|
-
self.login = email unless email.blank?
|
41
|
-
end
|
42
|
-
end
|
43
|
-
end
|
44
|
-
```
|
45
|
-
|
46
|
-
The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:
|
47
|
-
|
48
|
-
```ruby
|
49
|
-
class User < ActiveRecord::Base
|
50
|
-
validates :login, :email, presence: true
|
51
|
-
|
52
|
-
before_create do
|
53
|
-
self.name = login.capitalize if name.blank?
|
54
|
-
end
|
55
|
-
end
|
56
|
-
```
|
57
|
-
|
58
|
-
Callbacks can also be registered to only fire on certain life cycle events:
|
59
|
-
|
60
|
-
```ruby
|
61
|
-
class User < ActiveRecord::Base
|
62
|
-
before_validation :normalize_name, on: :create
|
63
|
-
|
64
|
-
# :on takes an array as well
|
65
|
-
after_validation :set_location, on: [ :create, :update ]
|
66
|
-
|
67
|
-
protected
|
68
|
-
def normalize_name
|
69
|
-
self.name = self.name.downcase.titleize
|
70
|
-
end
|
71
|
-
|
72
|
-
def set_location
|
73
|
-
self.location = LocationService.query(self)
|
74
|
-
end
|
75
|
-
end
|
76
|
-
```
|
77
|
-
|
78
|
-
It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
|
79
|
-
|
80
|
-
Available Callbacks
|
81
|
-
-------------------
|
82
|
-
|
83
|
-
Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:
|
84
|
-
|
85
|
-
### Creating an Object
|
86
|
-
|
87
|
-
* `before_validation`
|
88
|
-
* `after_validation`
|
89
|
-
* `before_save`
|
90
|
-
* `around_save`
|
91
|
-
* `before_create`
|
92
|
-
* `around_create`
|
93
|
-
* `after_create`
|
94
|
-
* `after_save`
|
95
|
-
|
96
|
-
### Updating an Object
|
97
|
-
|
98
|
-
* `before_validation`
|
99
|
-
* `after_validation`
|
100
|
-
* `before_save`
|
101
|
-
* `around_save`
|
102
|
-
* `before_update`
|
103
|
-
* `around_update`
|
104
|
-
* `after_update`
|
105
|
-
* `after_save`
|
106
|
-
|
107
|
-
### Destroying an Object
|
108
|
-
|
109
|
-
* `before_destroy`
|
110
|
-
* `around_destroy`
|
111
|
-
* `after_destroy`
|
112
|
-
|
113
|
-
WARNING. `after_save` runs both on create and update, but always _after_ the more specific callbacks `after_create` and `after_update`, no matter the order in which the macro calls were executed.
|
114
|
-
|
115
|
-
### `after_initialize` and `after_find`
|
116
|
-
|
117
|
-
The `after_initialize` callback will be called whenever an Active Record object is instantiated, either by directly using `new` or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record `initialize` method.
|
118
|
-
|
119
|
-
The `after_find` callback will be called whenever Active Record loads a record from the database. `after_find` is called before `after_initialize` if both are defined.
|
120
|
-
|
121
|
-
The `after_initialize` and `after_find` callbacks have no `before_*` counterparts, but they can be registered just like the other Active Record callbacks.
|
122
|
-
|
123
|
-
```ruby
|
124
|
-
class User < ActiveRecord::Base
|
125
|
-
after_initialize do |user|
|
126
|
-
puts "You have initialized an object!"
|
127
|
-
end
|
128
|
-
|
129
|
-
after_find do |user|
|
130
|
-
puts "You have found an object!"
|
131
|
-
end
|
132
|
-
end
|
133
|
-
|
134
|
-
>> User.new
|
135
|
-
You have initialized an object!
|
136
|
-
=> #<User id: nil>
|
137
|
-
|
138
|
-
>> User.first
|
139
|
-
You have found an object!
|
140
|
-
You have initialized an object!
|
141
|
-
=> #<User id: 1>
|
142
|
-
```
|
143
|
-
|
144
|
-
### `after_touch`
|
145
|
-
|
146
|
-
The `after_touch` callback will be called whenever an Active Record object is touched.
|
147
|
-
|
148
|
-
```ruby
|
149
|
-
class User < ActiveRecord::Base
|
150
|
-
after_touch do |user|
|
151
|
-
puts "You have touched an object"
|
152
|
-
end
|
153
|
-
end
|
154
|
-
|
155
|
-
>> u = User.create(name: 'Kuldeep')
|
156
|
-
=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">
|
157
|
-
|
158
|
-
>> u.touch
|
159
|
-
You have touched an object
|
160
|
-
=> true
|
161
|
-
```
|
162
|
-
|
163
|
-
It can be used along with `belongs_to`:
|
164
|
-
|
165
|
-
```ruby
|
166
|
-
class Employee < ActiveRecord::Base
|
167
|
-
belongs_to :company, touch: true
|
168
|
-
after_touch do
|
169
|
-
puts 'An Employee was touched'
|
170
|
-
end
|
171
|
-
end
|
172
|
-
|
173
|
-
class Company < ActiveRecord::Base
|
174
|
-
has_many :employees
|
175
|
-
after_touch :log_when_employees_or_company_touched
|
176
|
-
|
177
|
-
private
|
178
|
-
def log_when_employees_or_company_touched
|
179
|
-
puts 'Employee/Company was touched'
|
180
|
-
end
|
181
|
-
end
|
182
|
-
|
183
|
-
>> @employee = Employee.last
|
184
|
-
=> #<Employee id: 1, company_id: 1, created_at: "2013-11-25 17:04:22", updated_at: "2013-11-25 17:05:05">
|
185
|
-
|
186
|
-
# triggers @employee.company.touch
|
187
|
-
>> @employee.touch
|
188
|
-
Employee/Company was touched
|
189
|
-
An Employee was touched
|
190
|
-
=> true
|
191
|
-
```
|
192
|
-
|
193
|
-
Running Callbacks
|
194
|
-
-----------------
|
195
|
-
|
196
|
-
The following methods trigger callbacks:
|
197
|
-
|
198
|
-
* `create`
|
199
|
-
* `create!`
|
200
|
-
* `decrement!`
|
201
|
-
* `destroy`
|
202
|
-
* `destroy!`
|
203
|
-
* `destroy_all`
|
204
|
-
* `increment!`
|
205
|
-
* `save`
|
206
|
-
* `save!`
|
207
|
-
* `save(validate: false)`
|
208
|
-
* `toggle!`
|
209
|
-
* `update_attribute`
|
210
|
-
* `update`
|
211
|
-
* `update!`
|
212
|
-
* `valid?`
|
213
|
-
|
214
|
-
Additionally, the `after_find` callback is triggered by the following finder methods:
|
215
|
-
|
216
|
-
* `all`
|
217
|
-
* `first`
|
218
|
-
* `find`
|
219
|
-
* `find_by`
|
220
|
-
* `find_by_*`
|
221
|
-
* `find_by_*!`
|
222
|
-
* `find_by_sql`
|
223
|
-
* `last`
|
224
|
-
|
225
|
-
The `after_initialize` callback is triggered every time a new object of the class is initialized.
|
226
|
-
|
227
|
-
NOTE: The `find_by_*` and `find_by_*!` methods are dynamic finders generated automatically for every attribute. Learn more about them at the [Dynamic finders section](active_record_querying.html#dynamic-finders)
|
228
|
-
|
229
|
-
Skipping Callbacks
|
230
|
-
------------------
|
231
|
-
|
232
|
-
Just as with validations, it is also possible to skip callbacks by using the following methods:
|
233
|
-
|
234
|
-
* `decrement`
|
235
|
-
* `decrement_counter`
|
236
|
-
* `delete`
|
237
|
-
* `delete_all`
|
238
|
-
* `increment`
|
239
|
-
* `increment_counter`
|
240
|
-
* `toggle`
|
241
|
-
* `touch`
|
242
|
-
* `update_column`
|
243
|
-
* `update_columns`
|
244
|
-
* `update_all`
|
245
|
-
* `update_counters`
|
246
|
-
|
247
|
-
These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
|
248
|
-
|
249
|
-
Halting Execution
|
250
|
-
-----------------
|
251
|
-
|
252
|
-
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
|
253
|
-
|
254
|
-
The whole callback chain is wrapped in a transaction. If any _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception.
|
255
|
-
|
256
|
-
WARNING. Any exception that is not `ActiveRecord::Rollback` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` may break code that does not expect methods like `save` and `update_attributes` (which normally try to return `true` or `false`) to raise an exception.
|
257
|
-
|
258
|
-
Relational Callbacks
|
259
|
-
--------------------
|
260
|
-
|
261
|
-
Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user's posts should be destroyed if the user is destroyed. Let's add an `after_destroy` callback to the `User` model by way of its relationship to the `Post` model:
|
262
|
-
|
263
|
-
```ruby
|
264
|
-
class User < ActiveRecord::Base
|
265
|
-
has_many :posts, dependent: :destroy
|
266
|
-
end
|
267
|
-
|
268
|
-
class Post < ActiveRecord::Base
|
269
|
-
after_destroy :log_destroy_action
|
270
|
-
|
271
|
-
def log_destroy_action
|
272
|
-
puts 'Post destroyed'
|
273
|
-
end
|
274
|
-
end
|
275
|
-
|
276
|
-
>> user = User.first
|
277
|
-
=> #<User id: 1>
|
278
|
-
>> user.posts.create!
|
279
|
-
=> #<Post id: 1, user_id: 1>
|
280
|
-
>> user.destroy
|
281
|
-
Post destroyed
|
282
|
-
=> #<User id: 1>
|
283
|
-
```
|
284
|
-
|
285
|
-
Conditional Callbacks
|
286
|
-
---------------------
|
287
|
-
|
288
|
-
As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the `:if` and `:unless` options, which can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if` option when you want to specify under which conditions the callback **should** be called. If you want to specify the conditions under which the callback **should not** be called, then you may use the `:unless` option.
|
289
|
-
|
290
|
-
### Using `:if` and `:unless` with a `Symbol`
|
291
|
-
|
292
|
-
You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the `:if` option, the callback won't be executed if the predicate method returns false; when using the `:unless` option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.
|
293
|
-
|
294
|
-
```ruby
|
295
|
-
class Order < ActiveRecord::Base
|
296
|
-
before_save :normalize_card_number, if: :paid_with_card?
|
297
|
-
end
|
298
|
-
```
|
299
|
-
|
300
|
-
### Using `:if` and `:unless` with a String
|
301
|
-
|
302
|
-
You can also use a string that will be evaluated using `eval` and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
|
303
|
-
|
304
|
-
```ruby
|
305
|
-
class Order < ActiveRecord::Base
|
306
|
-
before_save :normalize_card_number, if: "paid_with_card?"
|
307
|
-
end
|
308
|
-
```
|
309
|
-
|
310
|
-
### Using `:if` and `:unless` with a `Proc`
|
311
|
-
|
312
|
-
Finally, it is possible to associate `:if` and `:unless` with a `Proc` object. This option is best suited when writing short validation methods, usually one-liners:
|
313
|
-
|
314
|
-
```ruby
|
315
|
-
class Order < ActiveRecord::Base
|
316
|
-
before_save :normalize_card_number,
|
317
|
-
if: Proc.new { |order| order.paid_with_card? }
|
318
|
-
end
|
319
|
-
```
|
320
|
-
|
321
|
-
### Multiple Conditions for Callbacks
|
322
|
-
|
323
|
-
When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration:
|
324
|
-
|
325
|
-
```ruby
|
326
|
-
class Comment < ActiveRecord::Base
|
327
|
-
after_create :send_email_to_author, if: :author_wants_emails?,
|
328
|
-
unless: Proc.new { |comment| comment.post.ignore_comments? }
|
329
|
-
end
|
330
|
-
```
|
331
|
-
|
332
|
-
Callback Classes
|
333
|
-
----------------
|
334
|
-
|
335
|
-
Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
|
336
|
-
|
337
|
-
Here's an example where we create a class with an `after_destroy` callback for a `PictureFile` model:
|
338
|
-
|
339
|
-
```ruby
|
340
|
-
class PictureFileCallbacks
|
341
|
-
def after_destroy(picture_file)
|
342
|
-
if File.exist?(picture_file.filepath)
|
343
|
-
File.delete(picture_file.filepath)
|
344
|
-
end
|
345
|
-
end
|
346
|
-
end
|
347
|
-
```
|
348
|
-
|
349
|
-
When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
|
350
|
-
|
351
|
-
```ruby
|
352
|
-
class PictureFile < ActiveRecord::Base
|
353
|
-
after_destroy PictureFileCallbacks.new
|
354
|
-
end
|
355
|
-
```
|
356
|
-
|
357
|
-
Note that we needed to instantiate a new `PictureFileCallbacks` object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:
|
358
|
-
|
359
|
-
```ruby
|
360
|
-
class PictureFileCallbacks
|
361
|
-
def self.after_destroy(picture_file)
|
362
|
-
if File.exist?(picture_file.filepath)
|
363
|
-
File.delete(picture_file.filepath)
|
364
|
-
end
|
365
|
-
end
|
366
|
-
end
|
367
|
-
```
|
368
|
-
|
369
|
-
If the callback method is declared this way, it won't be necessary to instantiate a `PictureFileCallbacks` object.
|
370
|
-
|
371
|
-
```ruby
|
372
|
-
class PictureFile < ActiveRecord::Base
|
373
|
-
after_destroy PictureFileCallbacks
|
374
|
-
end
|
375
|
-
```
|
376
|
-
|
377
|
-
You can declare as many callbacks as you want inside your callback classes.
|
378
|
-
|
379
|
-
Transaction Callbacks
|
380
|
-
---------------------
|
381
|
-
|
382
|
-
There are two additional callbacks that are triggered by the completion of a database transaction: `after_commit` and `after_rollback`. These callbacks are very similar to the `after_save` callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.
|
383
|
-
|
384
|
-
Consider, for example, the previous example where the `PictureFile` model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the `after_destroy` callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that `picture_file_2` in the code below is not valid and the `save!` method raises an error.
|
385
|
-
|
386
|
-
```ruby
|
387
|
-
PictureFile.transaction do
|
388
|
-
picture_file_1.destroy
|
389
|
-
picture_file_2.save!
|
390
|
-
end
|
391
|
-
```
|
392
|
-
|
393
|
-
By using the `after_commit` callback we can account for this case.
|
394
|
-
|
395
|
-
```ruby
|
396
|
-
class PictureFile < ActiveRecord::Base
|
397
|
-
after_commit :delete_picture_file_from_disk, on: [:destroy]
|
398
|
-
|
399
|
-
def delete_picture_file_from_disk
|
400
|
-
if File.exist?(filepath)
|
401
|
-
File.delete(filepath)
|
402
|
-
end
|
403
|
-
end
|
404
|
-
end
|
405
|
-
```
|
406
|
-
|
407
|
-
NOTE: the `:on` option specifies when a callback will be fired. If you
|
408
|
-
don't supply the `:on` option the callback will fire for every action.
|
409
|
-
|
410
|
-
WARNING. The `after_commit` and `after_rollback` callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
|
@@ -1,1785 +0,0 @@
|
|
1
|
-
Active Record Query Interface
|
2
|
-
=============================
|
3
|
-
|
4
|
-
This guide covers different ways to retrieve data from the database using Active Record.
|
5
|
-
|
6
|
-
After reading this guide, you will know:
|
7
|
-
|
8
|
-
* How to find records using a variety of methods and conditions.
|
9
|
-
* How to specify the order, retrieved attributes, grouping, and other properties of the found records.
|
10
|
-
* How to use eager loading to reduce the number of database queries needed for data retrieval.
|
11
|
-
* How to use dynamic finders methods.
|
12
|
-
* How to check for the existence of particular records.
|
13
|
-
* How to perform various calculations on Active Record models.
|
14
|
-
* How to run EXPLAIN on relations.
|
15
|
-
|
16
|
-
--------------------------------------------------------------------------------
|
17
|
-
|
18
|
-
If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
|
19
|
-
|
20
|
-
Code examples throughout this guide will refer to one or more of the following models:
|
21
|
-
|
22
|
-
TIP: All of the following models use `id` as the primary key, unless specified otherwise.
|
23
|
-
|
24
|
-
```ruby
|
25
|
-
class Client < ActiveRecord::Base
|
26
|
-
has_one :address
|
27
|
-
has_many :orders
|
28
|
-
has_and_belongs_to_many :roles
|
29
|
-
end
|
30
|
-
```
|
31
|
-
|
32
|
-
```ruby
|
33
|
-
class Address < ActiveRecord::Base
|
34
|
-
belongs_to :client
|
35
|
-
end
|
36
|
-
```
|
37
|
-
|
38
|
-
```ruby
|
39
|
-
class Order < ActiveRecord::Base
|
40
|
-
belongs_to :client, counter_cache: true
|
41
|
-
end
|
42
|
-
```
|
43
|
-
|
44
|
-
```ruby
|
45
|
-
class Role < ActiveRecord::Base
|
46
|
-
has_and_belongs_to_many :clients
|
47
|
-
end
|
48
|
-
```
|
49
|
-
|
50
|
-
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
|
51
|
-
|
52
|
-
Retrieving Objects from the Database
|
53
|
-
------------------------------------
|
54
|
-
|
55
|
-
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
|
56
|
-
|
57
|
-
The methods are:
|
58
|
-
|
59
|
-
* `bind`
|
60
|
-
* `create_with`
|
61
|
-
* `distinct`
|
62
|
-
* `eager_load`
|
63
|
-
* `extending`
|
64
|
-
* `from`
|
65
|
-
* `group`
|
66
|
-
* `having`
|
67
|
-
* `includes`
|
68
|
-
* `joins`
|
69
|
-
* `limit`
|
70
|
-
* `lock`
|
71
|
-
* `none`
|
72
|
-
* `offset`
|
73
|
-
* `order`
|
74
|
-
* `preload`
|
75
|
-
* `readonly`
|
76
|
-
* `references`
|
77
|
-
* `reorder`
|
78
|
-
* `reverse_order`
|
79
|
-
* `select`
|
80
|
-
* `uniq`
|
81
|
-
* `where`
|
82
|
-
|
83
|
-
All of the above methods return an instance of `ActiveRecord::Relation`.
|
84
|
-
|
85
|
-
The primary operation of `Model.find(options)` can be summarized as:
|
86
|
-
|
87
|
-
* Convert the supplied options to an equivalent SQL query.
|
88
|
-
* Fire the SQL query and retrieve the corresponding results from the database.
|
89
|
-
* Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
|
90
|
-
* Run `after_find` callbacks, if any.
|
91
|
-
|
92
|
-
### Retrieving a Single Object
|
93
|
-
|
94
|
-
Active Record provides several different ways of retrieving a single object.
|
95
|
-
|
96
|
-
#### Using a Primary Key
|
97
|
-
|
98
|
-
Using `Model.find(primary_key)`, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
|
99
|
-
|
100
|
-
```ruby
|
101
|
-
# Find the client with primary key (id) 10.
|
102
|
-
client = Client.find(10)
|
103
|
-
# => #<Client id: 10, first_name: "Ryan">
|
104
|
-
```
|
105
|
-
|
106
|
-
The SQL equivalent of the above is:
|
107
|
-
|
108
|
-
```sql
|
109
|
-
SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
|
110
|
-
```
|
111
|
-
|
112
|
-
`Model.find(primary_key)` will raise an `ActiveRecord::RecordNotFound` exception if no matching record is found.
|
113
|
-
|
114
|
-
#### `take`
|
115
|
-
|
116
|
-
`Model.take` retrieves a record without any implicit ordering. For example:
|
117
|
-
|
118
|
-
```ruby
|
119
|
-
client = Client.take
|
120
|
-
# => #<Client id: 1, first_name: "Lifo">
|
121
|
-
```
|
122
|
-
|
123
|
-
The SQL equivalent of the above is:
|
124
|
-
|
125
|
-
```sql
|
126
|
-
SELECT * FROM clients LIMIT 1
|
127
|
-
```
|
128
|
-
|
129
|
-
`Model.take` returns `nil` if no record is found and no exception will be raised.
|
130
|
-
|
131
|
-
TIP: The retrieved record may vary depending on the database engine.
|
132
|
-
|
133
|
-
#### `first`
|
134
|
-
|
135
|
-
`Model.first` finds the first record ordered by the primary key. For example:
|
136
|
-
|
137
|
-
```ruby
|
138
|
-
client = Client.first
|
139
|
-
# => #<Client id: 1, first_name: "Lifo">
|
140
|
-
```
|
141
|
-
|
142
|
-
The SQL equivalent of the above is:
|
143
|
-
|
144
|
-
```sql
|
145
|
-
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
|
146
|
-
```
|
147
|
-
|
148
|
-
`Model.first` returns `nil` if no matching record is found and no exception will be raised.
|
149
|
-
|
150
|
-
#### `last`
|
151
|
-
|
152
|
-
`Model.last` finds the last record ordered by the primary key. For example:
|
153
|
-
|
154
|
-
```ruby
|
155
|
-
client = Client.last
|
156
|
-
# => #<Client id: 221, first_name: "Russel">
|
157
|
-
```
|
158
|
-
|
159
|
-
The SQL equivalent of the above is:
|
160
|
-
|
161
|
-
```sql
|
162
|
-
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
|
163
|
-
```
|
164
|
-
|
165
|
-
`Model.last` returns `nil` if no matching record is found and no exception will be raised.
|
166
|
-
|
167
|
-
#### `find_by`
|
168
|
-
|
169
|
-
`Model.find_by` finds the first record matching some conditions. For example:
|
170
|
-
|
171
|
-
```ruby
|
172
|
-
Client.find_by first_name: 'Lifo'
|
173
|
-
# => #<Client id: 1, first_name: "Lifo">
|
174
|
-
|
175
|
-
Client.find_by first_name: 'Jon'
|
176
|
-
# => nil
|
177
|
-
```
|
178
|
-
|
179
|
-
It is equivalent to writing:
|
180
|
-
|
181
|
-
```ruby
|
182
|
-
Client.where(first_name: 'Lifo').take
|
183
|
-
```
|
184
|
-
|
185
|
-
#### `take!`
|
186
|
-
|
187
|
-
`Model.take!` retrieves a record without any implicit ordering. For example:
|
188
|
-
|
189
|
-
```ruby
|
190
|
-
client = Client.take!
|
191
|
-
# => #<Client id: 1, first_name: "Lifo">
|
192
|
-
```
|
193
|
-
|
194
|
-
The SQL equivalent of the above is:
|
195
|
-
|
196
|
-
```sql
|
197
|
-
SELECT * FROM clients LIMIT 1
|
198
|
-
```
|
199
|
-
|
200
|
-
`Model.take!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
|
201
|
-
|
202
|
-
#### `first!`
|
203
|
-
|
204
|
-
`Model.first!` finds the first record ordered by the primary key. For example:
|
205
|
-
|
206
|
-
```ruby
|
207
|
-
client = Client.first!
|
208
|
-
# => #<Client id: 1, first_name: "Lifo">
|
209
|
-
```
|
210
|
-
|
211
|
-
The SQL equivalent of the above is:
|
212
|
-
|
213
|
-
```sql
|
214
|
-
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
|
215
|
-
```
|
216
|
-
|
217
|
-
`Model.first!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
|
218
|
-
|
219
|
-
#### `last!`
|
220
|
-
|
221
|
-
`Model.last!` finds the last record ordered by the primary key. For example:
|
222
|
-
|
223
|
-
```ruby
|
224
|
-
client = Client.last!
|
225
|
-
# => #<Client id: 221, first_name: "Russel">
|
226
|
-
```
|
227
|
-
|
228
|
-
The SQL equivalent of the above is:
|
229
|
-
|
230
|
-
```sql
|
231
|
-
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
|
232
|
-
```
|
233
|
-
|
234
|
-
`Model.last!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
|
235
|
-
|
236
|
-
#### `find_by!`
|
237
|
-
|
238
|
-
`Model.find_by!` finds the first record matching some conditions. It raises `ActiveRecord::RecordNotFound` if no matching record is found. For example:
|
239
|
-
|
240
|
-
```ruby
|
241
|
-
Client.find_by! first_name: 'Lifo'
|
242
|
-
# => #<Client id: 1, first_name: "Lifo">
|
243
|
-
|
244
|
-
Client.find_by! first_name: 'Jon'
|
245
|
-
# => ActiveRecord::RecordNotFound
|
246
|
-
```
|
247
|
-
|
248
|
-
It is equivalent to writing:
|
249
|
-
|
250
|
-
```ruby
|
251
|
-
Client.where(first_name: 'Lifo').take!
|
252
|
-
```
|
253
|
-
|
254
|
-
### Retrieving Multiple Objects
|
255
|
-
|
256
|
-
#### Using Multiple Primary Keys
|
257
|
-
|
258
|
-
`Model.find(array_of_primary_key)` accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
|
259
|
-
|
260
|
-
```ruby
|
261
|
-
# Find the clients with primary keys 1 and 10.
|
262
|
-
client = Client.find([1, 10]) # Or even Client.find(1, 10)
|
263
|
-
# => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]
|
264
|
-
```
|
265
|
-
|
266
|
-
The SQL equivalent of the above is:
|
267
|
-
|
268
|
-
```sql
|
269
|
-
SELECT * FROM clients WHERE (clients.id IN (1,10))
|
270
|
-
```
|
271
|
-
|
272
|
-
WARNING: `Model.find(array_of_primary_key)` will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for **all** of the supplied primary keys.
|
273
|
-
|
274
|
-
#### take
|
275
|
-
|
276
|
-
`Model.take(limit)` retrieves the first number of records specified by `limit` without any explicit ordering:
|
277
|
-
|
278
|
-
```ruby
|
279
|
-
Client.take(2)
|
280
|
-
# => [#<Client id: 1, first_name: "Lifo">,
|
281
|
-
#<Client id: 2, first_name: "Raf">]
|
282
|
-
```
|
283
|
-
|
284
|
-
The SQL equivalent of the above is:
|
285
|
-
|
286
|
-
```sql
|
287
|
-
SELECT * FROM clients LIMIT 2
|
288
|
-
```
|
289
|
-
|
290
|
-
#### first
|
291
|
-
|
292
|
-
`Model.first(limit)` finds the first number of records specified by `limit` ordered by primary key:
|
293
|
-
|
294
|
-
```ruby
|
295
|
-
Client.first(2)
|
296
|
-
# => [#<Client id: 1, first_name: "Lifo">,
|
297
|
-
#<Client id: 2, first_name: "Raf">]
|
298
|
-
```
|
299
|
-
|
300
|
-
The SQL equivalent of the above is:
|
301
|
-
|
302
|
-
```sql
|
303
|
-
SELECT * FROM clients ORDER BY id ASC LIMIT 2
|
304
|
-
```
|
305
|
-
|
306
|
-
#### last
|
307
|
-
|
308
|
-
`Model.last(limit)` finds the number of records specified by `limit` ordered by primary key in descending order:
|
309
|
-
|
310
|
-
```ruby
|
311
|
-
Client.last(2)
|
312
|
-
# => [#<Client id: 10, first_name: "Ryan">,
|
313
|
-
#<Client id: 9, first_name: "John">]
|
314
|
-
```
|
315
|
-
|
316
|
-
The SQL equivalent of the above is:
|
317
|
-
|
318
|
-
```sql
|
319
|
-
SELECT * FROM clients ORDER BY id DESC LIMIT 2
|
320
|
-
```
|
321
|
-
|
322
|
-
### Retrieving Multiple Objects in Batches
|
323
|
-
|
324
|
-
We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data.
|
325
|
-
|
326
|
-
This may appear straightforward:
|
327
|
-
|
328
|
-
```ruby
|
329
|
-
# This is very inefficient when the users table has thousands of rows.
|
330
|
-
User.all.each do |user|
|
331
|
-
NewsLetter.weekly_deliver(user)
|
332
|
-
end
|
333
|
-
```
|
334
|
-
|
335
|
-
But this approach becomes increasingly impractical as the table size increases, since `User.all.each` instructs Active Record to fetch _the entire table_ in a single pass, build a model object per row, and then keep the entire array of model objects in memory. Indeed, if we have a large number of records, the entire collection may exceed the amount of memory available.
|
336
|
-
|
337
|
-
Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, `find_each`, retrieves a batch of records and then yields _each_ record to the block individually as a model. The second method, `find_in_batches`, retrieves a batch of records and then yields _the entire batch_ to the block as an array of models.
|
338
|
-
|
339
|
-
TIP: The `find_each` and `find_in_batches` methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records the regular find methods are the preferred option.
|
340
|
-
|
341
|
-
#### `find_each`
|
342
|
-
|
343
|
-
The `find_each` method retrieves a batch of records and then yields _each_ record to the block individually as a model. In the following example, `find_each` will retrieve 1000 records (the current default for both `find_each` and `find_in_batches`) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:
|
344
|
-
|
345
|
-
```ruby
|
346
|
-
User.find_each do |user|
|
347
|
-
NewsLetter.weekly_deliver(user)
|
348
|
-
end
|
349
|
-
```
|
350
|
-
|
351
|
-
##### Options for `find_each`
|
352
|
-
|
353
|
-
The `find_each` method accepts most of the options allowed by the regular `find` method, except for `:order` and `:limit`, which are reserved for internal use by `find_each`.
|
354
|
-
|
355
|
-
Two additional options, `:batch_size` and `:start`, are available as well.
|
356
|
-
|
357
|
-
**`:batch_size`**
|
358
|
-
|
359
|
-
The `:batch_size` option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5000:
|
360
|
-
|
361
|
-
```ruby
|
362
|
-
User.find_each(batch_size: 5000) do |user|
|
363
|
-
NewsLetter.weekly_deliver(user)
|
364
|
-
end
|
365
|
-
```
|
366
|
-
|
367
|
-
**`:start`**
|
368
|
-
|
369
|
-
By default, records are fetched in ascending order of the primary key, which must be an integer. The `:start` option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.
|
370
|
-
|
371
|
-
For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:
|
372
|
-
|
373
|
-
```ruby
|
374
|
-
User.find_each(start: 2000, batch_size: 5000) do |user|
|
375
|
-
NewsLetter.weekly_deliver(user)
|
376
|
-
end
|
377
|
-
```
|
378
|
-
|
379
|
-
Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate `:start` option on each worker.
|
380
|
-
|
381
|
-
#### `find_in_batches`
|
382
|
-
|
383
|
-
The `find_in_batches` method is similar to `find_each`, since both retrieve batches of records. The difference is that `find_in_batches` yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:
|
384
|
-
|
385
|
-
```ruby
|
386
|
-
# Give add_invoices an array of 1000 invoices at a time
|
387
|
-
Invoice.find_in_batches(include: :invoice_lines) do |invoices|
|
388
|
-
export.add_invoices(invoices)
|
389
|
-
end
|
390
|
-
```
|
391
|
-
|
392
|
-
NOTE: The `:include` option allows you to name associations that should be loaded alongside with the models.
|
393
|
-
|
394
|
-
##### Options for `find_in_batches`
|
395
|
-
|
396
|
-
The `find_in_batches` method accepts the same `:batch_size` and `:start` options as `find_each`, as well as most of the options allowed by the regular `find` method, except for `:order` and `:limit`, which are reserved for internal use by `find_in_batches`.
|
397
|
-
|
398
|
-
Conditions
|
399
|
-
----------
|
400
|
-
|
401
|
-
The `where` method allows you to specify conditions to limit the records returned, representing the `WHERE`-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
|
402
|
-
|
403
|
-
### Pure String Conditions
|
404
|
-
|
405
|
-
If you'd like to add conditions to your find, you could just specify them in there, just like `Client.where("orders_count = '2'")`. This will find all clients where the `orders_count` field's value is 2.
|
406
|
-
|
407
|
-
WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, `Client.where("first_name LIKE '%#{params[:first_name]}%'")` is not safe. See the next section for the preferred way to handle conditions using an array.
|
408
|
-
|
409
|
-
### Array Conditions
|
410
|
-
|
411
|
-
Now what if that number could vary, say as an argument from somewhere? The find would then take the form:
|
412
|
-
|
413
|
-
```ruby
|
414
|
-
Client.where("orders_count = ?", params[:orders])
|
415
|
-
```
|
416
|
-
|
417
|
-
Active Record will go through the first element in the conditions value and any additional elements will replace the question marks `(?)` in the first element.
|
418
|
-
|
419
|
-
If you want to specify multiple conditions:
|
420
|
-
|
421
|
-
```ruby
|
422
|
-
Client.where("orders_count = ? AND locked = ?", params[:orders], false)
|
423
|
-
```
|
424
|
-
|
425
|
-
In this example, the first question mark will be replaced with the value in `params[:orders]` and the second will be replaced with the SQL representation of `false`, which depends on the adapter.
|
426
|
-
|
427
|
-
This code is highly preferable:
|
428
|
-
|
429
|
-
```ruby
|
430
|
-
Client.where("orders_count = ?", params[:orders])
|
431
|
-
```
|
432
|
-
|
433
|
-
to this code:
|
434
|
-
|
435
|
-
```ruby
|
436
|
-
Client.where("orders_count = #{params[:orders]}")
|
437
|
-
```
|
438
|
-
|
439
|
-
because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database **as-is**. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out they can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
|
440
|
-
|
441
|
-
TIP: For more information on the dangers of SQL injection, see the [Ruby on Rails Security Guide](security.html#sql-injection).
|
442
|
-
|
443
|
-
#### Placeholder Conditions
|
444
|
-
|
445
|
-
Similar to the `(?)` replacement style of params, you can also specify keys/values hash in your array conditions:
|
446
|
-
|
447
|
-
```ruby
|
448
|
-
Client.where("created_at >= :start_date AND created_at <= :end_date",
|
449
|
-
{start_date: params[:start_date], end_date: params[:end_date]})
|
450
|
-
```
|
451
|
-
|
452
|
-
This makes for clearer readability if you have a large number of variable conditions.
|
453
|
-
|
454
|
-
### Hash Conditions
|
455
|
-
|
456
|
-
Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
|
457
|
-
|
458
|
-
NOTE: Only equality, range and subset checking are possible with Hash conditions.
|
459
|
-
|
460
|
-
#### Equality Conditions
|
461
|
-
|
462
|
-
```ruby
|
463
|
-
Client.where(locked: true)
|
464
|
-
```
|
465
|
-
|
466
|
-
The field name can also be a string:
|
467
|
-
|
468
|
-
```ruby
|
469
|
-
Client.where('locked' => true)
|
470
|
-
```
|
471
|
-
|
472
|
-
In the case of a belongs_to relationship, an association key can be used to specify the model if an Active Record object is used as the value. This method works with polymorphic relationships as well.
|
473
|
-
|
474
|
-
```ruby
|
475
|
-
Post.where(author: author)
|
476
|
-
Author.joins(:posts).where(posts: { author: author })
|
477
|
-
```
|
478
|
-
|
479
|
-
NOTE: The values cannot be symbols. For example, you cannot do `Client.where(status: :active)`.
|
480
|
-
|
481
|
-
#### Range Conditions
|
482
|
-
|
483
|
-
```ruby
|
484
|
-
Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
|
485
|
-
```
|
486
|
-
|
487
|
-
This will find all clients created yesterday by using a `BETWEEN` SQL statement:
|
488
|
-
|
489
|
-
```sql
|
490
|
-
SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
|
491
|
-
```
|
492
|
-
|
493
|
-
This demonstrates a shorter syntax for the examples in [Array Conditions](#array-conditions)
|
494
|
-
|
495
|
-
#### Subset Conditions
|
496
|
-
|
497
|
-
If you want to find records using the `IN` expression you can pass an array to the conditions hash:
|
498
|
-
|
499
|
-
```ruby
|
500
|
-
Client.where(orders_count: [1,3,5])
|
501
|
-
```
|
502
|
-
|
503
|
-
This code will generate SQL like this:
|
504
|
-
|
505
|
-
```sql
|
506
|
-
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
|
507
|
-
```
|
508
|
-
|
509
|
-
### NOT Conditions
|
510
|
-
|
511
|
-
`NOT` SQL queries can be built by `where.not`.
|
512
|
-
|
513
|
-
```ruby
|
514
|
-
Post.where.not(author: author)
|
515
|
-
```
|
516
|
-
|
517
|
-
In other words, this query can be generated by calling `where` with no argument, then immediately chain with `not` passing `where` conditions.
|
518
|
-
|
519
|
-
Ordering
|
520
|
-
--------
|
521
|
-
|
522
|
-
To retrieve records from the database in a specific order, you can use the `order` method.
|
523
|
-
|
524
|
-
For example, if you're getting a set of records and want to order them in ascending order by the `created_at` field in your table:
|
525
|
-
|
526
|
-
```ruby
|
527
|
-
Client.order(:created_at)
|
528
|
-
# OR
|
529
|
-
Client.order("created_at")
|
530
|
-
```
|
531
|
-
|
532
|
-
You could specify `ASC` or `DESC` as well:
|
533
|
-
|
534
|
-
```ruby
|
535
|
-
Client.order(created_at: :desc)
|
536
|
-
# OR
|
537
|
-
Client.order(created_at: :asc)
|
538
|
-
# OR
|
539
|
-
Client.order("created_at DESC")
|
540
|
-
# OR
|
541
|
-
Client.order("created_at ASC")
|
542
|
-
```
|
543
|
-
|
544
|
-
Or ordering by multiple fields:
|
545
|
-
|
546
|
-
```ruby
|
547
|
-
Client.order(orders_count: :asc, created_at: :desc)
|
548
|
-
# OR
|
549
|
-
Client.order(:orders_count, created_at: :desc)
|
550
|
-
# OR
|
551
|
-
Client.order("orders_count ASC, created_at DESC")
|
552
|
-
# OR
|
553
|
-
Client.order("orders_count ASC", "created_at DESC")
|
554
|
-
```
|
555
|
-
|
556
|
-
If you want to call `order` multiple times e.g. in different context, new order will append previous one
|
557
|
-
|
558
|
-
```ruby
|
559
|
-
Client.order("orders_count ASC").order("created_at DESC")
|
560
|
-
# SELECT * FROM clients ORDER BY orders_count ASC, created_at DESC
|
561
|
-
```
|
562
|
-
|
563
|
-
Selecting Specific Fields
|
564
|
-
-------------------------
|
565
|
-
|
566
|
-
By default, `Model.find` selects all the fields from the result set using `select *`.
|
567
|
-
|
568
|
-
To select only a subset of fields from the result set, you can specify the subset via the `select` method.
|
569
|
-
|
570
|
-
For example, to select only `viewable_by` and `locked` columns:
|
571
|
-
|
572
|
-
```ruby
|
573
|
-
Client.select("viewable_by, locked")
|
574
|
-
```
|
575
|
-
|
576
|
-
The SQL query used by this find call will be somewhat like:
|
577
|
-
|
578
|
-
```sql
|
579
|
-
SELECT viewable_by, locked FROM clients
|
580
|
-
```
|
581
|
-
|
582
|
-
Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive:
|
583
|
-
|
584
|
-
```bash
|
585
|
-
ActiveModel::MissingAttributeError: missing attribute: <attribute>
|
586
|
-
```
|
587
|
-
|
588
|
-
Where `<attribute>` is the attribute you asked for. The `id` method will not raise the `ActiveRecord::MissingAttributeError`, so just be careful when working with associations because they need the `id` method to function properly.
|
589
|
-
|
590
|
-
If you would like to only grab a single record per unique value in a certain field, you can use `distinct`:
|
591
|
-
|
592
|
-
```ruby
|
593
|
-
Client.select(:name).distinct
|
594
|
-
```
|
595
|
-
|
596
|
-
This would generate SQL like:
|
597
|
-
|
598
|
-
```sql
|
599
|
-
SELECT DISTINCT name FROM clients
|
600
|
-
```
|
601
|
-
|
602
|
-
You can also remove the uniqueness constraint:
|
603
|
-
|
604
|
-
```ruby
|
605
|
-
query = Client.select(:name).distinct
|
606
|
-
# => Returns unique names
|
607
|
-
|
608
|
-
query.distinct(false)
|
609
|
-
# => Returns all names, even if there are duplicates
|
610
|
-
```
|
611
|
-
|
612
|
-
Limit and Offset
|
613
|
-
----------------
|
614
|
-
|
615
|
-
To apply `LIMIT` to the SQL fired by the `Model.find`, you can specify the `LIMIT` using `limit` and `offset` methods on the relation.
|
616
|
-
|
617
|
-
You can use `limit` to specify the number of records to be retrieved, and use `offset` to specify the number of records to skip before starting to return the records. For example
|
618
|
-
|
619
|
-
```ruby
|
620
|
-
Client.limit(5)
|
621
|
-
```
|
622
|
-
|
623
|
-
will return a maximum of 5 clients and because it specifies no offset it will return the first 5 in the table. The SQL it executes looks like this:
|
624
|
-
|
625
|
-
```sql
|
626
|
-
SELECT * FROM clients LIMIT 5
|
627
|
-
```
|
628
|
-
|
629
|
-
Adding `offset` to that
|
630
|
-
|
631
|
-
```ruby
|
632
|
-
Client.limit(5).offset(30)
|
633
|
-
```
|
634
|
-
|
635
|
-
will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:
|
636
|
-
|
637
|
-
```sql
|
638
|
-
SELECT * FROM clients LIMIT 5 OFFSET 30
|
639
|
-
```
|
640
|
-
|
641
|
-
Group
|
642
|
-
-----
|
643
|
-
|
644
|
-
To apply a `GROUP BY` clause to the SQL fired by the finder, you can specify the `group` method on the find.
|
645
|
-
|
646
|
-
For example, if you want to find a collection of the dates orders were created on:
|
647
|
-
|
648
|
-
```ruby
|
649
|
-
Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
|
650
|
-
```
|
651
|
-
|
652
|
-
And this will give you a single `Order` object for each date where there are orders in the database.
|
653
|
-
|
654
|
-
The SQL that would be executed would be something like this:
|
655
|
-
|
656
|
-
```sql
|
657
|
-
SELECT date(created_at) as ordered_date, sum(price) as total_price
|
658
|
-
FROM orders
|
659
|
-
GROUP BY date(created_at)
|
660
|
-
```
|
661
|
-
|
662
|
-
Having
|
663
|
-
------
|
664
|
-
|
665
|
-
SQL uses the `HAVING` clause to specify conditions on the `GROUP BY` fields. You can add the `HAVING` clause to the SQL fired by the `Model.find` by adding the `:having` option to the find.
|
666
|
-
|
667
|
-
For example:
|
668
|
-
|
669
|
-
```ruby
|
670
|
-
Order.select("date(created_at) as ordered_date, sum(price) as total_price").
|
671
|
-
group("date(created_at)").having("sum(price) > ?", 100)
|
672
|
-
```
|
673
|
-
|
674
|
-
The SQL that would be executed would be something like this:
|
675
|
-
|
676
|
-
```sql
|
677
|
-
SELECT date(created_at) as ordered_date, sum(price) as total_price
|
678
|
-
FROM orders
|
679
|
-
GROUP BY date(created_at)
|
680
|
-
HAVING sum(price) > 100
|
681
|
-
```
|
682
|
-
|
683
|
-
This will return single order objects for each day, but only those that are ordered more than $100 in a day.
|
684
|
-
|
685
|
-
Overriding Conditions
|
686
|
-
---------------------
|
687
|
-
|
688
|
-
### `unscope`
|
689
|
-
|
690
|
-
You can specify certain conditions to be removed using the `unscope` method. For example:
|
691
|
-
|
692
|
-
```ruby
|
693
|
-
Post.where('id > 10').limit(20).order('id asc').except(:order)
|
694
|
-
```
|
695
|
-
|
696
|
-
The SQL that would be executed:
|
697
|
-
|
698
|
-
```sql
|
699
|
-
SELECT * FROM posts WHERE id > 10 LIMIT 20
|
700
|
-
|
701
|
-
# Original query without `unscope`
|
702
|
-
SELECT * FROM posts WHERE id > 10 ORDER BY id asc LIMIT 20
|
703
|
-
|
704
|
-
```
|
705
|
-
|
706
|
-
You can additionally unscope specific where clauses. For example:
|
707
|
-
|
708
|
-
```ruby
|
709
|
-
Post.where(id: 10, trashed: false).unscope(where: :id)
|
710
|
-
# SELECT "posts".* FROM "posts" WHERE trashed = 0
|
711
|
-
```
|
712
|
-
|
713
|
-
A relation which has used `unscope` will affect any relation it is
|
714
|
-
merged in to:
|
715
|
-
|
716
|
-
```ruby
|
717
|
-
Post.order('id asc').merge(Post.unscope(:order))
|
718
|
-
# SELECT "posts".* FROM "posts"
|
719
|
-
```
|
720
|
-
|
721
|
-
### `only`
|
722
|
-
|
723
|
-
You can also override conditions using the `only` method. For example:
|
724
|
-
|
725
|
-
```ruby
|
726
|
-
Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
|
727
|
-
```
|
728
|
-
|
729
|
-
The SQL that would be executed:
|
730
|
-
|
731
|
-
```sql
|
732
|
-
SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
|
733
|
-
|
734
|
-
# Original query without `only`
|
735
|
-
SELECT "posts".* FROM "posts" WHERE (id > 10) ORDER BY id desc LIMIT 20
|
736
|
-
|
737
|
-
```
|
738
|
-
|
739
|
-
### `reorder`
|
740
|
-
|
741
|
-
The `reorder` method overrides the default scope order. For example:
|
742
|
-
|
743
|
-
```ruby
|
744
|
-
class Post < ActiveRecord::Base
|
745
|
-
..
|
746
|
-
..
|
747
|
-
has_many :comments, -> { order('posted_at DESC') }
|
748
|
-
end
|
749
|
-
|
750
|
-
Post.find(10).comments.reorder('name')
|
751
|
-
```
|
752
|
-
|
753
|
-
The SQL that would be executed:
|
754
|
-
|
755
|
-
```sql
|
756
|
-
SELECT * FROM posts WHERE id = 10
|
757
|
-
SELECT * FROM comments WHERE post_id = 10 ORDER BY name
|
758
|
-
```
|
759
|
-
|
760
|
-
In case the `reorder` clause is not used, the SQL executed would be:
|
761
|
-
|
762
|
-
```sql
|
763
|
-
SELECT * FROM posts WHERE id = 10
|
764
|
-
SELECT * FROM comments WHERE post_id = 10 ORDER BY posted_at DESC
|
765
|
-
```
|
766
|
-
|
767
|
-
### `reverse_order`
|
768
|
-
|
769
|
-
The `reverse_order` method reverses the ordering clause if specified.
|
770
|
-
|
771
|
-
```ruby
|
772
|
-
Client.where("orders_count > 10").order(:name).reverse_order
|
773
|
-
```
|
774
|
-
|
775
|
-
The SQL that would be executed:
|
776
|
-
|
777
|
-
```sql
|
778
|
-
SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
|
779
|
-
```
|
780
|
-
|
781
|
-
If no ordering clause is specified in the query, the `reverse_order` orders by the primary key in reverse order.
|
782
|
-
|
783
|
-
```ruby
|
784
|
-
Client.where("orders_count > 10").reverse_order
|
785
|
-
```
|
786
|
-
|
787
|
-
The SQL that would be executed:
|
788
|
-
|
789
|
-
```sql
|
790
|
-
SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
|
791
|
-
```
|
792
|
-
|
793
|
-
This method accepts **no** arguments.
|
794
|
-
|
795
|
-
### `rewhere`
|
796
|
-
|
797
|
-
The `rewhere` method overrides an existing, named where condition. For example:
|
798
|
-
|
799
|
-
```ruby
|
800
|
-
Post.where(trashed: true).rewhere(trashed: false)
|
801
|
-
```
|
802
|
-
|
803
|
-
The SQL that would be executed:
|
804
|
-
|
805
|
-
```sql
|
806
|
-
SELECT * FROM posts WHERE `trashed` = 0
|
807
|
-
```
|
808
|
-
|
809
|
-
In case the `rewhere` clause is not used,
|
810
|
-
|
811
|
-
```ruby
|
812
|
-
Post.where(trashed: true).where(trashed: false)
|
813
|
-
```
|
814
|
-
|
815
|
-
the SQL executed would be:
|
816
|
-
|
817
|
-
```sql
|
818
|
-
SELECT * FROM posts WHERE `trashed` = 1 AND `trashed` = 0
|
819
|
-
```
|
820
|
-
|
821
|
-
Null Relation
|
822
|
-
-------------
|
823
|
-
|
824
|
-
The `none` method returns a chainable relation with no records. Any subsequent conditions chained to the returned relation will continue generating empty relations. This is useful in scenarios where you need a chainable response to a method or a scope that could return zero results.
|
825
|
-
|
826
|
-
```ruby
|
827
|
-
Post.none # returns an empty Relation and fires no queries.
|
828
|
-
```
|
829
|
-
|
830
|
-
```ruby
|
831
|
-
# The visible_posts method below is expected to return a Relation.
|
832
|
-
@posts = current_user.visible_posts.where(name: params[:name])
|
833
|
-
|
834
|
-
def visible_posts
|
835
|
-
case role
|
836
|
-
when 'Country Manager'
|
837
|
-
Post.where(country: country)
|
838
|
-
when 'Reviewer'
|
839
|
-
Post.published
|
840
|
-
when 'Bad User'
|
841
|
-
Post.none # => returning [] or nil breaks the caller code in this case
|
842
|
-
end
|
843
|
-
end
|
844
|
-
```
|
845
|
-
|
846
|
-
Readonly Objects
|
847
|
-
----------------
|
848
|
-
|
849
|
-
Active Record provides `readonly` method on a relation to explicitly disallow modification of any of the returned objects. Any attempt to alter a readonly record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` exception.
|
850
|
-
|
851
|
-
```ruby
|
852
|
-
client = Client.readonly.first
|
853
|
-
client.visits += 1
|
854
|
-
client.save
|
855
|
-
```
|
856
|
-
|
857
|
-
As `client` is explicitly set to be a readonly object, the above code will raise an `ActiveRecord::ReadOnlyRecord` exception when calling `client.save` with an updated value of _visits_.
|
858
|
-
|
859
|
-
Locking Records for Update
|
860
|
-
--------------------------
|
861
|
-
|
862
|
-
Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
|
863
|
-
|
864
|
-
Active Record provides two locking mechanisms:
|
865
|
-
|
866
|
-
* Optimistic Locking
|
867
|
-
* Pessimistic Locking
|
868
|
-
|
869
|
-
### Optimistic Locking
|
870
|
-
|
871
|
-
Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An `ActiveRecord::StaleObjectError` exception is thrown if that has occurred and the update is ignored.
|
872
|
-
|
873
|
-
**Optimistic locking column**
|
874
|
-
|
875
|
-
In order to use optimistic locking, the table needs to have a column called `lock_version` of type integer. Each time the record is updated, Active Record increments the `lock_version` column. If an update request is made with a lower value in the `lock_version` field than is currently in the `lock_version` column in the database, the update request will fail with an `ActiveRecord::StaleObjectError`. Example:
|
876
|
-
|
877
|
-
```ruby
|
878
|
-
c1 = Client.find(1)
|
879
|
-
c2 = Client.find(1)
|
880
|
-
|
881
|
-
c1.first_name = "Michael"
|
882
|
-
c1.save
|
883
|
-
|
884
|
-
c2.name = "should fail"
|
885
|
-
c2.save # Raises an ActiveRecord::StaleObjectError
|
886
|
-
```
|
887
|
-
|
888
|
-
You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
|
889
|
-
|
890
|
-
This behavior can be turned off by setting `ActiveRecord::Base.lock_optimistically = false`.
|
891
|
-
|
892
|
-
To override the name of the `lock_version` column, `ActiveRecord::Base` provides a class attribute called `locking_column`:
|
893
|
-
|
894
|
-
```ruby
|
895
|
-
class Client < ActiveRecord::Base
|
896
|
-
self.locking_column = :lock_client_column
|
897
|
-
end
|
898
|
-
```
|
899
|
-
|
900
|
-
### Pessimistic Locking
|
901
|
-
|
902
|
-
Pessimistic locking uses a locking mechanism provided by the underlying database. Using `lock` when building a relation obtains an exclusive lock on the selected rows. Relations using `lock` are usually wrapped inside a transaction for preventing deadlock conditions.
|
903
|
-
|
904
|
-
For example:
|
905
|
-
|
906
|
-
```ruby
|
907
|
-
Item.transaction do
|
908
|
-
i = Item.lock.first
|
909
|
-
i.name = 'Jones'
|
910
|
-
i.save
|
911
|
-
end
|
912
|
-
```
|
913
|
-
|
914
|
-
The above session produces the following SQL for a MySQL backend:
|
915
|
-
|
916
|
-
```sql
|
917
|
-
SQL (0.2ms) BEGIN
|
918
|
-
Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
|
919
|
-
Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
|
920
|
-
SQL (0.8ms) COMMIT
|
921
|
-
```
|
922
|
-
|
923
|
-
You can also pass raw SQL to the `lock` method for allowing different types of locks. For example, MySQL has an expression called `LOCK IN SHARE MODE` where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:
|
924
|
-
|
925
|
-
```ruby
|
926
|
-
Item.transaction do
|
927
|
-
i = Item.lock("LOCK IN SHARE MODE").find(1)
|
928
|
-
i.increment!(:views)
|
929
|
-
end
|
930
|
-
```
|
931
|
-
|
932
|
-
If you already have an instance of your model, you can start a transaction and acquire the lock in one go using the following code:
|
933
|
-
|
934
|
-
```ruby
|
935
|
-
item = Item.first
|
936
|
-
item.with_lock do
|
937
|
-
# This block is called within a transaction,
|
938
|
-
# item is already locked.
|
939
|
-
item.increment!(:views)
|
940
|
-
end
|
941
|
-
```
|
942
|
-
|
943
|
-
Joining Tables
|
944
|
-
--------------
|
945
|
-
|
946
|
-
Active Record provides a finder method called `joins` for specifying `JOIN` clauses on the resulting SQL. There are multiple ways to use the `joins` method.
|
947
|
-
|
948
|
-
### Using a String SQL Fragment
|
949
|
-
|
950
|
-
You can just supply the raw SQL specifying the `JOIN` clause to `joins`:
|
951
|
-
|
952
|
-
```ruby
|
953
|
-
Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
|
954
|
-
```
|
955
|
-
|
956
|
-
This will result in the following SQL:
|
957
|
-
|
958
|
-
```sql
|
959
|
-
SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
|
960
|
-
```
|
961
|
-
|
962
|
-
### Using Array/Hash of Named Associations
|
963
|
-
|
964
|
-
WARNING: This method only works with `INNER JOIN`.
|
965
|
-
|
966
|
-
Active Record lets you use the names of the [associations](association_basics.html) defined on the model as a shortcut for specifying `JOIN` clause for those associations when using the `joins` method.
|
967
|
-
|
968
|
-
For example, consider the following `Category`, `Post`, `Comment`, `Guest` and `Tag` models:
|
969
|
-
|
970
|
-
```ruby
|
971
|
-
class Category < ActiveRecord::Base
|
972
|
-
has_many :posts
|
973
|
-
end
|
974
|
-
|
975
|
-
class Post < ActiveRecord::Base
|
976
|
-
belongs_to :category
|
977
|
-
has_many :comments
|
978
|
-
has_many :tags
|
979
|
-
end
|
980
|
-
|
981
|
-
class Comment < ActiveRecord::Base
|
982
|
-
belongs_to :post
|
983
|
-
has_one :guest
|
984
|
-
end
|
985
|
-
|
986
|
-
class Guest < ActiveRecord::Base
|
987
|
-
belongs_to :comment
|
988
|
-
end
|
989
|
-
|
990
|
-
class Tag < ActiveRecord::Base
|
991
|
-
belongs_to :post
|
992
|
-
end
|
993
|
-
```
|
994
|
-
|
995
|
-
Now all of the following will produce the expected join queries using `INNER JOIN`:
|
996
|
-
|
997
|
-
#### Joining a Single Association
|
998
|
-
|
999
|
-
```ruby
|
1000
|
-
Category.joins(:posts)
|
1001
|
-
```
|
1002
|
-
|
1003
|
-
This produces:
|
1004
|
-
|
1005
|
-
```sql
|
1006
|
-
SELECT categories.* FROM categories
|
1007
|
-
INNER JOIN posts ON posts.category_id = categories.id
|
1008
|
-
```
|
1009
|
-
|
1010
|
-
Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use `Category.joins(:posts).uniq`.
|
1011
|
-
|
1012
|
-
#### Joining Multiple Associations
|
1013
|
-
|
1014
|
-
```ruby
|
1015
|
-
Post.joins(:category, :comments)
|
1016
|
-
```
|
1017
|
-
|
1018
|
-
This produces:
|
1019
|
-
|
1020
|
-
```sql
|
1021
|
-
SELECT posts.* FROM posts
|
1022
|
-
INNER JOIN categories ON posts.category_id = categories.id
|
1023
|
-
INNER JOIN comments ON comments.post_id = posts.id
|
1024
|
-
```
|
1025
|
-
|
1026
|
-
Or, in English: "return all posts that have a category and at least one comment". Note again that posts with multiple comments will show up multiple times.
|
1027
|
-
|
1028
|
-
#### Joining Nested Associations (Single Level)
|
1029
|
-
|
1030
|
-
```ruby
|
1031
|
-
Post.joins(comments: :guest)
|
1032
|
-
```
|
1033
|
-
|
1034
|
-
This produces:
|
1035
|
-
|
1036
|
-
```sql
|
1037
|
-
SELECT posts.* FROM posts
|
1038
|
-
INNER JOIN comments ON comments.post_id = posts.id
|
1039
|
-
INNER JOIN guests ON guests.comment_id = comments.id
|
1040
|
-
```
|
1041
|
-
|
1042
|
-
Or, in English: "return all posts that have a comment made by a guest."
|
1043
|
-
|
1044
|
-
#### Joining Nested Associations (Multiple Level)
|
1045
|
-
|
1046
|
-
```ruby
|
1047
|
-
Category.joins(posts: [{ comments: :guest }, :tags])
|
1048
|
-
```
|
1049
|
-
|
1050
|
-
This produces:
|
1051
|
-
|
1052
|
-
```sql
|
1053
|
-
SELECT categories.* FROM categories
|
1054
|
-
INNER JOIN posts ON posts.category_id = categories.id
|
1055
|
-
INNER JOIN comments ON comments.post_id = posts.id
|
1056
|
-
INNER JOIN guests ON guests.comment_id = comments.id
|
1057
|
-
INNER JOIN tags ON tags.post_id = posts.id
|
1058
|
-
```
|
1059
|
-
|
1060
|
-
### Specifying Conditions on the Joined Tables
|
1061
|
-
|
1062
|
-
You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provides a special syntax for specifying conditions for the joined tables:
|
1063
|
-
|
1064
|
-
```ruby
|
1065
|
-
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
|
1066
|
-
Client.joins(:orders).where('orders.created_at' => time_range)
|
1067
|
-
```
|
1068
|
-
|
1069
|
-
An alternative and cleaner syntax is to nest the hash conditions:
|
1070
|
-
|
1071
|
-
```ruby
|
1072
|
-
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
|
1073
|
-
Client.joins(:orders).where(orders: { created_at: time_range })
|
1074
|
-
```
|
1075
|
-
|
1076
|
-
This will find all clients who have orders that were created yesterday, again using a `BETWEEN` SQL expression.
|
1077
|
-
|
1078
|
-
Eager Loading Associations
|
1079
|
-
--------------------------
|
1080
|
-
|
1081
|
-
Eager loading is the mechanism for loading the associated records of the objects returned by `Model.find` using as few queries as possible.
|
1082
|
-
|
1083
|
-
**N + 1 queries problem**
|
1084
|
-
|
1085
|
-
Consider the following code, which finds 10 clients and prints their postcodes:
|
1086
|
-
|
1087
|
-
```ruby
|
1088
|
-
clients = Client.limit(10)
|
1089
|
-
|
1090
|
-
clients.each do |client|
|
1091
|
-
puts client.address.postcode
|
1092
|
-
end
|
1093
|
-
```
|
1094
|
-
|
1095
|
-
This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total.
|
1096
|
-
|
1097
|
-
**Solution to N + 1 queries problem**
|
1098
|
-
|
1099
|
-
Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the `includes` method of the `Model.find` call. With `includes`, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
|
1100
|
-
|
1101
|
-
Revisiting the above case, we could rewrite `Client.limit(10)` to use eager load addresses:
|
1102
|
-
|
1103
|
-
```ruby
|
1104
|
-
clients = Client.includes(:address).limit(10)
|
1105
|
-
|
1106
|
-
clients.each do |client|
|
1107
|
-
puts client.address.postcode
|
1108
|
-
end
|
1109
|
-
```
|
1110
|
-
|
1111
|
-
The above code will execute just **2** queries, as opposed to **11** queries in the previous case:
|
1112
|
-
|
1113
|
-
```sql
|
1114
|
-
SELECT * FROM clients LIMIT 10
|
1115
|
-
SELECT addresses.* FROM addresses
|
1116
|
-
WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
|
1117
|
-
```
|
1118
|
-
|
1119
|
-
### Eager Loading Multiple Associations
|
1120
|
-
|
1121
|
-
Active Record lets you eager load any number of associations with a single `Model.find` call by using an array, hash, or a nested hash of array/hash with the `includes` method.
|
1122
|
-
|
1123
|
-
#### Array of Multiple Associations
|
1124
|
-
|
1125
|
-
```ruby
|
1126
|
-
Post.includes(:category, :comments)
|
1127
|
-
```
|
1128
|
-
|
1129
|
-
This loads all the posts and the associated category and comments for each post.
|
1130
|
-
|
1131
|
-
#### Nested Associations Hash
|
1132
|
-
|
1133
|
-
```ruby
|
1134
|
-
Category.includes(posts: [{ comments: :guest }, :tags]).find(1)
|
1135
|
-
```
|
1136
|
-
|
1137
|
-
This will find the category with id 1 and eager load all of the associated posts, the associated posts' tags and comments, and every comment's guest association.
|
1138
|
-
|
1139
|
-
### Specifying Conditions on Eager Loaded Associations
|
1140
|
-
|
1141
|
-
Even though Active Record lets you specify conditions on the eager loaded associations just like `joins`, the recommended way is to use [joins](#joining-tables) instead.
|
1142
|
-
|
1143
|
-
However if you must do this, you may use `where` as you would normally.
|
1144
|
-
|
1145
|
-
```ruby
|
1146
|
-
Post.includes(:comments).where(comments: { visible: true })
|
1147
|
-
```
|
1148
|
-
|
1149
|
-
This would generate a query which contains a `LEFT OUTER JOIN` whereas the
|
1150
|
-
`joins` method would generate one using the `INNER JOIN` function instead.
|
1151
|
-
|
1152
|
-
```ruby
|
1153
|
-
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)
|
1154
|
-
```
|
1155
|
-
|
1156
|
-
If there was no `where` condition, this would generate the normal set of two
|
1157
|
-
queries.
|
1158
|
-
|
1159
|
-
NOTE: Using `where` like this will only work when you pass it a Hash. For
|
1160
|
-
SQL-fragments you need use `references` to force joined tables:
|
1161
|
-
|
1162
|
-
```ruby
|
1163
|
-
Post.includes(:comments).where("comments.visible = true").references(:comments)
|
1164
|
-
```
|
1165
|
-
|
1166
|
-
If, in the case of this `includes` query, there were no comments for any posts,
|
1167
|
-
all the posts would still be loaded. By using `joins` (an INNER JOIN), the join
|
1168
|
-
conditions **must** match, otherwise no records will be returned.
|
1169
|
-
|
1170
|
-
|
1171
|
-
Scopes
|
1172
|
-
------
|
1173
|
-
|
1174
|
-
Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as `where`, `joins` and `includes`. All scope methods will return an `ActiveRecord::Relation` object which will allow for further methods (such as other scopes) to be called on it.
|
1175
|
-
|
1176
|
-
To define a simple scope, we use the `scope` method inside the class, passing the query that we'd like to run when this scope is called:
|
1177
|
-
|
1178
|
-
```ruby
|
1179
|
-
class Post < ActiveRecord::Base
|
1180
|
-
scope :published, -> { where(published: true) }
|
1181
|
-
end
|
1182
|
-
```
|
1183
|
-
|
1184
|
-
This is exactly the same as defining a class method, and which you use is a matter of personal preference:
|
1185
|
-
|
1186
|
-
```ruby
|
1187
|
-
class Post < ActiveRecord::Base
|
1188
|
-
def self.published
|
1189
|
-
where(published: true)
|
1190
|
-
end
|
1191
|
-
end
|
1192
|
-
```
|
1193
|
-
|
1194
|
-
Scopes are also chainable within scopes:
|
1195
|
-
|
1196
|
-
```ruby
|
1197
|
-
class Post < ActiveRecord::Base
|
1198
|
-
scope :published, -> { where(published: true) }
|
1199
|
-
scope :published_and_commented, -> { published.where("comments_count > 0") }
|
1200
|
-
end
|
1201
|
-
```
|
1202
|
-
|
1203
|
-
To call this `published` scope we can call it on either the class:
|
1204
|
-
|
1205
|
-
```ruby
|
1206
|
-
Post.published # => [published posts]
|
1207
|
-
```
|
1208
|
-
|
1209
|
-
Or on an association consisting of `Post` objects:
|
1210
|
-
|
1211
|
-
```ruby
|
1212
|
-
category = Category.first
|
1213
|
-
category.posts.published # => [published posts belonging to this category]
|
1214
|
-
```
|
1215
|
-
|
1216
|
-
### Passing in arguments
|
1217
|
-
|
1218
|
-
Your scope can take arguments:
|
1219
|
-
|
1220
|
-
```ruby
|
1221
|
-
class Post < ActiveRecord::Base
|
1222
|
-
scope :created_before, ->(time) { where("created_at < ?", time) }
|
1223
|
-
end
|
1224
|
-
```
|
1225
|
-
|
1226
|
-
Call the scope as if it were a class method:
|
1227
|
-
|
1228
|
-
```ruby
|
1229
|
-
Post.created_before(Time.zone.now)
|
1230
|
-
```
|
1231
|
-
|
1232
|
-
However, this is just duplicating the functionality that would be provided to you by a class method.
|
1233
|
-
|
1234
|
-
```ruby
|
1235
|
-
class Post < ActiveRecord::Base
|
1236
|
-
def self.created_before(time)
|
1237
|
-
where("created_at < ?", time)
|
1238
|
-
end
|
1239
|
-
end
|
1240
|
-
```
|
1241
|
-
|
1242
|
-
Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
|
1243
|
-
|
1244
|
-
```ruby
|
1245
|
-
category.posts.created_before(time)
|
1246
|
-
```
|
1247
|
-
|
1248
|
-
### Merging of scopes
|
1249
|
-
|
1250
|
-
Just like `where` clauses scopes are merged using `AND` conditions.
|
1251
|
-
|
1252
|
-
```ruby
|
1253
|
-
class User < ActiveRecord::Base
|
1254
|
-
scope :active, -> { where state: 'active' }
|
1255
|
-
scope :inactive, -> { where state: 'inactive' }
|
1256
|
-
end
|
1257
|
-
|
1258
|
-
User.active.inactive
|
1259
|
-
# SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive'
|
1260
|
-
```
|
1261
|
-
|
1262
|
-
We can mix and match `scope` and `where` conditions and the final sql
|
1263
|
-
will have all conditions joined with `AND`.
|
1264
|
-
|
1265
|
-
```ruby
|
1266
|
-
User.active.where(state: 'finished')
|
1267
|
-
# SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'finished'
|
1268
|
-
```
|
1269
|
-
|
1270
|
-
If we do want the `last where clause` to win then `Relation#merge` can
|
1271
|
-
be used.
|
1272
|
-
|
1273
|
-
```ruby
|
1274
|
-
User.active.merge(User.inactive)
|
1275
|
-
# SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
|
1276
|
-
```
|
1277
|
-
|
1278
|
-
One important caveat is that `default_scope` will be prepended in
|
1279
|
-
`scope` and `where` conditions.
|
1280
|
-
|
1281
|
-
```ruby
|
1282
|
-
class User < ActiveRecord::Base
|
1283
|
-
default_scope { where state: 'pending' }
|
1284
|
-
scope :active, -> { where state: 'active' }
|
1285
|
-
scope :inactive, -> { where state: 'inactive' }
|
1286
|
-
end
|
1287
|
-
|
1288
|
-
User.all
|
1289
|
-
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
|
1290
|
-
|
1291
|
-
User.active
|
1292
|
-
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'
|
1293
|
-
|
1294
|
-
User.where(state: 'inactive')
|
1295
|
-
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
|
1296
|
-
```
|
1297
|
-
|
1298
|
-
As you can see above the `default_scope` is being merged in both
|
1299
|
-
`scope` and `where` conditions.
|
1300
|
-
|
1301
|
-
|
1302
|
-
### Applying a default scope
|
1303
|
-
|
1304
|
-
If we wish for a scope to be applied across all queries to the model we can use the
|
1305
|
-
`default_scope` method within the model itself.
|
1306
|
-
|
1307
|
-
```ruby
|
1308
|
-
class Client < ActiveRecord::Base
|
1309
|
-
default_scope { where("removed_at IS NULL") }
|
1310
|
-
end
|
1311
|
-
```
|
1312
|
-
|
1313
|
-
When queries are executed on this model, the SQL query will now look something like
|
1314
|
-
this:
|
1315
|
-
|
1316
|
-
```sql
|
1317
|
-
SELECT * FROM clients WHERE removed_at IS NULL
|
1318
|
-
```
|
1319
|
-
|
1320
|
-
If you need to do more complex things with a default scope, you can alternatively
|
1321
|
-
define it as a class method:
|
1322
|
-
|
1323
|
-
```ruby
|
1324
|
-
class Client < ActiveRecord::Base
|
1325
|
-
def self.default_scope
|
1326
|
-
# Should return an ActiveRecord::Relation.
|
1327
|
-
end
|
1328
|
-
end
|
1329
|
-
```
|
1330
|
-
|
1331
|
-
### Removing All Scoping
|
1332
|
-
|
1333
|
-
If we wish to remove scoping for any reason we can use the `unscoped` method. This is
|
1334
|
-
especially useful if a `default_scope` is specified in the model and should not be
|
1335
|
-
applied for this particular query.
|
1336
|
-
|
1337
|
-
```ruby
|
1338
|
-
Client.unscoped.load
|
1339
|
-
```
|
1340
|
-
|
1341
|
-
This method removes all scoping and will do a normal query on the table.
|
1342
|
-
|
1343
|
-
Note that chaining `unscoped` with a `scope` does not work. In these cases, it is
|
1344
|
-
recommended that you use the block form of `unscoped`:
|
1345
|
-
|
1346
|
-
```ruby
|
1347
|
-
Client.unscoped {
|
1348
|
-
Client.created_before(Time.zone.now)
|
1349
|
-
}
|
1350
|
-
```
|
1351
|
-
|
1352
|
-
Dynamic Finders
|
1353
|
-
---------------
|
1354
|
-
|
1355
|
-
For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called `first_name` on your `Client` model for example, you get `find_by_first_name` for free from Active Record. If you have a `locked` field on the `Client` model, you also get `find_by_locked` and methods.
|
1356
|
-
|
1357
|
-
You can specify an exclamation point (`!`) on the end of the dynamic finders to get them to raise an `ActiveRecord::RecordNotFound` error if they do not return any records, like `Client.find_by_name!("Ryan")`
|
1358
|
-
|
1359
|
-
If you want to find both by name and locked, you can chain these finders together by simply typing "`and`" between the fields. For example, `Client.find_by_first_name_and_locked("Ryan", true)`.
|
1360
|
-
|
1361
|
-
Find or Build a New Object
|
1362
|
-
--------------------------
|
1363
|
-
|
1364
|
-
NOTE: Some dynamic finders have been deprecated in Rails 4.0 and will be
|
1365
|
-
removed in Rails 4.1. The best practice is to use Active Record scopes
|
1366
|
-
instead. You can find the deprecation gem at
|
1367
|
-
https://github.com/rails/activerecord-deprecated_finders
|
1368
|
-
|
1369
|
-
It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods.
|
1370
|
-
|
1371
|
-
### `find_or_create_by`
|
1372
|
-
|
1373
|
-
The `find_or_create_by` method checks whether a record with the attributes exists. If it doesn't, then `create` is called. Let's see an example.
|
1374
|
-
|
1375
|
-
Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:
|
1376
|
-
|
1377
|
-
```ruby
|
1378
|
-
Client.find_or_create_by(first_name: 'Andy')
|
1379
|
-
# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
|
1380
|
-
```
|
1381
|
-
|
1382
|
-
The SQL generated by this method looks like this:
|
1383
|
-
|
1384
|
-
```sql
|
1385
|
-
SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
|
1386
|
-
BEGIN
|
1387
|
-
INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 1, NULL, '2011-08-30 05:22:57')
|
1388
|
-
COMMIT
|
1389
|
-
```
|
1390
|
-
|
1391
|
-
`find_or_create_by` returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned.
|
1392
|
-
|
1393
|
-
The new record might not be saved to the database; that depends on whether validations passed or not (just like `create`).
|
1394
|
-
|
1395
|
-
Suppose we want to set the 'locked' attribute to `false` if we're
|
1396
|
-
creating a new record, but we don't want to include it in the query. So
|
1397
|
-
we want to find the client named "Andy", or if that client doesn't
|
1398
|
-
exist, create a client named "Andy" which is not locked.
|
1399
|
-
|
1400
|
-
We can achieve this in two ways. The first is to use `create_with`:
|
1401
|
-
|
1402
|
-
```ruby
|
1403
|
-
Client.create_with(locked: false).find_or_create_by(first_name: 'Andy')
|
1404
|
-
```
|
1405
|
-
|
1406
|
-
The second way is using a block:
|
1407
|
-
|
1408
|
-
```ruby
|
1409
|
-
Client.find_or_create_by(first_name: 'Andy') do |c|
|
1410
|
-
c.locked = false
|
1411
|
-
end
|
1412
|
-
```
|
1413
|
-
|
1414
|
-
The block will only be executed if the client is being created. The
|
1415
|
-
second time we run this code, the block will be ignored.
|
1416
|
-
|
1417
|
-
### `find_or_create_by!`
|
1418
|
-
|
1419
|
-
You can also use `find_or_create_by!` to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add
|
1420
|
-
|
1421
|
-
```ruby
|
1422
|
-
validates :orders_count, presence: true
|
1423
|
-
```
|
1424
|
-
|
1425
|
-
to your `Client` model. If you try to create a new `Client` without passing an `orders_count`, the record will be invalid and an exception will be raised:
|
1426
|
-
|
1427
|
-
```ruby
|
1428
|
-
Client.find_or_create_by!(first_name: 'Andy')
|
1429
|
-
# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
|
1430
|
-
```
|
1431
|
-
|
1432
|
-
### `find_or_initialize_by`
|
1433
|
-
|
1434
|
-
The `find_or_initialize_by` method will work just like
|
1435
|
-
`find_or_create_by` but it will call `new` instead of `create`. This
|
1436
|
-
means that a new model instance will be created in memory but won't be
|
1437
|
-
saved to the database. Continuing with the `find_or_create_by` example, we
|
1438
|
-
now want the client named 'Nick':
|
1439
|
-
|
1440
|
-
```ruby
|
1441
|
-
nick = Client.find_or_initialize_by(first_name: 'Nick')
|
1442
|
-
# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
|
1443
|
-
|
1444
|
-
nick.persisted?
|
1445
|
-
# => false
|
1446
|
-
|
1447
|
-
nick.new_record?
|
1448
|
-
# => true
|
1449
|
-
```
|
1450
|
-
|
1451
|
-
Because the object is not yet stored in the database, the SQL generated looks like this:
|
1452
|
-
|
1453
|
-
```sql
|
1454
|
-
SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
|
1455
|
-
```
|
1456
|
-
|
1457
|
-
When you want to save it to the database, just call `save`:
|
1458
|
-
|
1459
|
-
```ruby
|
1460
|
-
nick.save
|
1461
|
-
# => true
|
1462
|
-
```
|
1463
|
-
|
1464
|
-
Finding by SQL
|
1465
|
-
--------------
|
1466
|
-
|
1467
|
-
If you'd like to use your own SQL to find records in a table you can use `find_by_sql`. The `find_by_sql` method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:
|
1468
|
-
|
1469
|
-
```ruby
|
1470
|
-
Client.find_by_sql("SELECT * FROM clients
|
1471
|
-
INNER JOIN orders ON clients.id = orders.client_id
|
1472
|
-
ORDER BY clients.created_at desc")
|
1473
|
-
```
|
1474
|
-
|
1475
|
-
`find_by_sql` provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
|
1476
|
-
|
1477
|
-
### `select_all`
|
1478
|
-
|
1479
|
-
`find_by_sql` has a close relative called `connection#select_all`. `select_all` will retrieve objects from the database using custom SQL just like `find_by_sql` but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
|
1480
|
-
|
1481
|
-
```ruby
|
1482
|
-
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
|
1483
|
-
```
|
1484
|
-
|
1485
|
-
### `pluck`
|
1486
|
-
|
1487
|
-
`pluck` can be used to query a single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
|
1488
|
-
|
1489
|
-
```ruby
|
1490
|
-
Client.where(active: true).pluck(:id)
|
1491
|
-
# SELECT id FROM clients WHERE active = 1
|
1492
|
-
# => [1, 2, 3]
|
1493
|
-
|
1494
|
-
Client.distinct.pluck(:role)
|
1495
|
-
# SELECT DISTINCT role FROM clients
|
1496
|
-
# => ['admin', 'member', 'guest']
|
1497
|
-
|
1498
|
-
Client.pluck(:id, :name)
|
1499
|
-
# SELECT clients.id, clients.name FROM clients
|
1500
|
-
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
|
1501
|
-
```
|
1502
|
-
|
1503
|
-
`pluck` makes it possible to replace code like:
|
1504
|
-
|
1505
|
-
```ruby
|
1506
|
-
Client.select(:id).map { |c| c.id }
|
1507
|
-
# or
|
1508
|
-
Client.select(:id).map(&:id)
|
1509
|
-
# or
|
1510
|
-
Client.select(:id, :name).map { |c| [c.id, c.name] }
|
1511
|
-
```
|
1512
|
-
|
1513
|
-
with:
|
1514
|
-
|
1515
|
-
```ruby
|
1516
|
-
Client.pluck(:id)
|
1517
|
-
# or
|
1518
|
-
Client.pluck(:id, :name)
|
1519
|
-
```
|
1520
|
-
|
1521
|
-
Unlike `select`, `pluck` directly converts a database result into a Ruby `Array`,
|
1522
|
-
without constructing `ActiveRecord` objects. This can mean better performance for
|
1523
|
-
a large or often-running query. However, any model method overrides will
|
1524
|
-
not be available. For example:
|
1525
|
-
|
1526
|
-
```ruby
|
1527
|
-
class Client < ActiveRecord::Base
|
1528
|
-
def name
|
1529
|
-
"I am #{super}"
|
1530
|
-
end
|
1531
|
-
end
|
1532
|
-
|
1533
|
-
Client.select(:name).map &:name
|
1534
|
-
# => ["I am David", "I am Jeremy", "I am Jose"]
|
1535
|
-
|
1536
|
-
Client.pluck(:name)
|
1537
|
-
# => ["David", "Jeremy", "Jose"]
|
1538
|
-
```
|
1539
|
-
|
1540
|
-
Furthermore, unlike `select` and other `Relation` scopes, `pluck` triggers an immediate
|
1541
|
-
query, and thus cannot be chained with any further scopes, although it can work with
|
1542
|
-
scopes already constructed earlier:
|
1543
|
-
|
1544
|
-
```ruby
|
1545
|
-
Client.pluck(:name).limit(1)
|
1546
|
-
# => NoMethodError: undefined method `limit' for #<Array:0x007ff34d3ad6d8>
|
1547
|
-
|
1548
|
-
Client.limit(1).pluck(:name)
|
1549
|
-
# => ["David"]
|
1550
|
-
```
|
1551
|
-
|
1552
|
-
### `ids`
|
1553
|
-
|
1554
|
-
`ids` can be used to pluck all the IDs for the relation using the table's primary key.
|
1555
|
-
|
1556
|
-
```ruby
|
1557
|
-
Person.ids
|
1558
|
-
# SELECT id FROM people
|
1559
|
-
```
|
1560
|
-
|
1561
|
-
```ruby
|
1562
|
-
class Person < ActiveRecord::Base
|
1563
|
-
self.primary_key = "person_id"
|
1564
|
-
end
|
1565
|
-
|
1566
|
-
Person.ids
|
1567
|
-
# SELECT person_id FROM people
|
1568
|
-
```
|
1569
|
-
|
1570
|
-
Existence of Objects
|
1571
|
-
--------------------
|
1572
|
-
|
1573
|
-
If you simply want to check for the existence of the object there's a method called `exists?`.
|
1574
|
-
This method will query the database using the same query as `find`, but instead of returning an
|
1575
|
-
object or collection of objects it will return either `true` or `false`.
|
1576
|
-
|
1577
|
-
```ruby
|
1578
|
-
Client.exists?(1)
|
1579
|
-
```
|
1580
|
-
|
1581
|
-
The `exists?` method also takes multiple values, but the catch is that it will return `true` if any
|
1582
|
-
one of those records exists.
|
1583
|
-
|
1584
|
-
```ruby
|
1585
|
-
Client.exists?(id: [1,2,3])
|
1586
|
-
# or
|
1587
|
-
Client.exists?(name: ['John', 'Sergei'])
|
1588
|
-
```
|
1589
|
-
|
1590
|
-
It's even possible to use `exists?` without any arguments on a model or a relation.
|
1591
|
-
|
1592
|
-
```ruby
|
1593
|
-
Client.where(first_name: 'Ryan').exists?
|
1594
|
-
```
|
1595
|
-
|
1596
|
-
The above returns `true` if there is at least one client with the `first_name` 'Ryan' and `false`
|
1597
|
-
otherwise.
|
1598
|
-
|
1599
|
-
```ruby
|
1600
|
-
Client.exists?
|
1601
|
-
```
|
1602
|
-
|
1603
|
-
The above returns `false` if the `clients` table is empty and `true` otherwise.
|
1604
|
-
|
1605
|
-
You can also use `any?` and `many?` to check for existence on a model or relation.
|
1606
|
-
|
1607
|
-
```ruby
|
1608
|
-
# via a model
|
1609
|
-
Post.any?
|
1610
|
-
Post.many?
|
1611
|
-
|
1612
|
-
# via a named scope
|
1613
|
-
Post.recent.any?
|
1614
|
-
Post.recent.many?
|
1615
|
-
|
1616
|
-
# via a relation
|
1617
|
-
Post.where(published: true).any?
|
1618
|
-
Post.where(published: true).many?
|
1619
|
-
|
1620
|
-
# via an association
|
1621
|
-
Post.first.categories.any?
|
1622
|
-
Post.first.categories.many?
|
1623
|
-
```
|
1624
|
-
|
1625
|
-
Calculations
|
1626
|
-
------------
|
1627
|
-
|
1628
|
-
This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
|
1629
|
-
|
1630
|
-
All calculation methods work directly on a model:
|
1631
|
-
|
1632
|
-
```ruby
|
1633
|
-
Client.count
|
1634
|
-
# SELECT count(*) AS count_all FROM clients
|
1635
|
-
```
|
1636
|
-
|
1637
|
-
Or on a relation:
|
1638
|
-
|
1639
|
-
```ruby
|
1640
|
-
Client.where(first_name: 'Ryan').count
|
1641
|
-
# SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
|
1642
|
-
```
|
1643
|
-
|
1644
|
-
You can also use various finder methods on a relation for performing complex calculations:
|
1645
|
-
|
1646
|
-
```ruby
|
1647
|
-
Client.includes("orders").where(first_name: 'Ryan', orders: { status: 'received' }).count
|
1648
|
-
```
|
1649
|
-
|
1650
|
-
Which will execute:
|
1651
|
-
|
1652
|
-
```sql
|
1653
|
-
SELECT count(DISTINCT clients.id) AS count_all FROM clients
|
1654
|
-
LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
|
1655
|
-
(clients.first_name = 'Ryan' AND orders.status = 'received')
|
1656
|
-
```
|
1657
|
-
|
1658
|
-
### Count
|
1659
|
-
|
1660
|
-
If you want to see how many records are in your model's table you could call `Client.count` and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use `Client.count(:age)`.
|
1661
|
-
|
1662
|
-
For options, please see the parent section, [Calculations](#calculations).
|
1663
|
-
|
1664
|
-
### Average
|
1665
|
-
|
1666
|
-
If you want to see the average of a certain number in one of your tables you can call the `average` method on the class that relates to the table. This method call will look something like this:
|
1667
|
-
|
1668
|
-
```ruby
|
1669
|
-
Client.average("orders_count")
|
1670
|
-
```
|
1671
|
-
|
1672
|
-
This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
|
1673
|
-
|
1674
|
-
For options, please see the parent section, [Calculations](#calculations).
|
1675
|
-
|
1676
|
-
### Minimum
|
1677
|
-
|
1678
|
-
If you want to find the minimum value of a field in your table you can call the `minimum` method on the class that relates to the table. This method call will look something like this:
|
1679
|
-
|
1680
|
-
```ruby
|
1681
|
-
Client.minimum("age")
|
1682
|
-
```
|
1683
|
-
|
1684
|
-
For options, please see the parent section, [Calculations](#calculations).
|
1685
|
-
|
1686
|
-
### Maximum
|
1687
|
-
|
1688
|
-
If you want to find the maximum value of a field in your table you can call the `maximum` method on the class that relates to the table. This method call will look something like this:
|
1689
|
-
|
1690
|
-
```ruby
|
1691
|
-
Client.maximum("age")
|
1692
|
-
```
|
1693
|
-
|
1694
|
-
For options, please see the parent section, [Calculations](#calculations).
|
1695
|
-
|
1696
|
-
### Sum
|
1697
|
-
|
1698
|
-
If you want to find the sum of a field for all records in your table you can call the `sum` method on the class that relates to the table. This method call will look something like this:
|
1699
|
-
|
1700
|
-
```ruby
|
1701
|
-
Client.sum("orders_count")
|
1702
|
-
```
|
1703
|
-
|
1704
|
-
For options, please see the parent section, [Calculations](#calculations).
|
1705
|
-
|
1706
|
-
Running EXPLAIN
|
1707
|
-
---------------
|
1708
|
-
|
1709
|
-
You can run EXPLAIN on the queries triggered by relations. For example,
|
1710
|
-
|
1711
|
-
```ruby
|
1712
|
-
User.where(id: 1).joins(:posts).explain
|
1713
|
-
```
|
1714
|
-
|
1715
|
-
may yield
|
1716
|
-
|
1717
|
-
```
|
1718
|
-
EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
|
1719
|
-
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
|
1720
|
-
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|
1721
|
-
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
|
1722
|
-
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
|
1723
|
-
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
|
1724
|
-
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
|
1725
|
-
2 rows in set (0.00 sec)
|
1726
|
-
```
|
1727
|
-
|
1728
|
-
under MySQL.
|
1729
|
-
|
1730
|
-
Active Record performs a pretty printing that emulates the one of the database
|
1731
|
-
shells. So, the same query running with the PostgreSQL adapter would yield instead
|
1732
|
-
|
1733
|
-
```
|
1734
|
-
EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "users"."id" = 1
|
1735
|
-
QUERY PLAN
|
1736
|
-
------------------------------------------------------------------------------
|
1737
|
-
Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
|
1738
|
-
Join Filter: (posts.user_id = users.id)
|
1739
|
-
-> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
|
1740
|
-
Index Cond: (id = 1)
|
1741
|
-
-> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
|
1742
|
-
Filter: (posts.user_id = 1)
|
1743
|
-
(6 rows)
|
1744
|
-
```
|
1745
|
-
|
1746
|
-
Eager loading may trigger more than one query under the hood, and some queries
|
1747
|
-
may need the results of previous ones. Because of that, `explain` actually
|
1748
|
-
executes the query, and then asks for the query plans. For example,
|
1749
|
-
|
1750
|
-
```ruby
|
1751
|
-
User.where(id: 1).includes(:posts).explain
|
1752
|
-
```
|
1753
|
-
|
1754
|
-
yields
|
1755
|
-
|
1756
|
-
```
|
1757
|
-
EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
|
1758
|
-
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
|
1759
|
-
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|
1760
|
-
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
|
1761
|
-
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
|
1762
|
-
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
|
1763
|
-
1 row in set (0.00 sec)
|
1764
|
-
|
1765
|
-
EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
|
1766
|
-
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
|
1767
|
-
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|
1768
|
-
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
|
1769
|
-
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
|
1770
|
-
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
|
1771
|
-
1 row in set (0.00 sec)
|
1772
|
-
```
|
1773
|
-
|
1774
|
-
under MySQL.
|
1775
|
-
|
1776
|
-
### Interpreting EXPLAIN
|
1777
|
-
|
1778
|
-
Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
|
1779
|
-
following pointers may be helpful:
|
1780
|
-
|
1781
|
-
* SQLite3: [EXPLAIN QUERY PLAN](http://www.sqlite.org/eqp.html)
|
1782
|
-
|
1783
|
-
* MySQL: [EXPLAIN Output Format](http://dev.mysql.com/doc/refman/5.6/en/explain-output.html)
|
1784
|
-
|
1785
|
-
* PostgreSQL: [Using EXPLAIN](http://www.postgresql.org/docs/current/static/using-explain.html)
|