rails 4.1.4 → 5.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (284) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +24 -18
  3. metadata +51 -304
  4. data/guides/CHANGELOG.md +0 -41
  5. data/guides/Rakefile +0 -77
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +0 -53
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -710
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -53
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/code/getting_started/Gemfile +0 -40
  148. data/guides/code/getting_started/Gemfile.lock +0 -125
  149. data/guides/code/getting_started/README.rdoc +0 -28
  150. data/guides/code/getting_started/Rakefile +0 -6
  151. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  152. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  153. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  154. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
  155. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  156. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  157. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  158. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
  159. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
  160. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
  161. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
  162. data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
  163. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  164. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  165. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
  166. data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
  167. data/guides/code/getting_started/app/models/comment.rb +0 -3
  168. data/guides/code/getting_started/app/models/post.rb +0 -7
  169. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  170. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  171. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  172. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
  173. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
  174. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
  175. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  176. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
  177. data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
  178. data/guides/code/getting_started/bin/bundle +0 -4
  179. data/guides/code/getting_started/bin/rails +0 -4
  180. data/guides/code/getting_started/bin/rake +0 -4
  181. data/guides/code/getting_started/config/application.rb +0 -18
  182. data/guides/code/getting_started/config/boot.rb +0 -4
  183. data/guides/code/getting_started/config/database.yml +0 -25
  184. data/guides/code/getting_started/config/environment.rb +0 -5
  185. data/guides/code/getting_started/config/environments/development.rb +0 -30
  186. data/guides/code/getting_started/config/environments/production.rb +0 -80
  187. data/guides/code/getting_started/config/environments/test.rb +0 -36
  188. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  189. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  190. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  191. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  192. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  193. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  194. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  195. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  196. data/guides/code/getting_started/config/locales/en.yml +0 -23
  197. data/guides/code/getting_started/config/routes.rb +0 -7
  198. data/guides/code/getting_started/config.ru +0 -4
  199. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
  200. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
  201. data/guides/code/getting_started/db/schema.rb +0 -33
  202. data/guides/code/getting_started/db/seeds.rb +0 -7
  203. data/guides/code/getting_started/public/404.html +0 -60
  204. data/guides/code/getting_started/public/422.html +0 -60
  205. data/guides/code/getting_started/public/500.html +0 -59
  206. data/guides/code/getting_started/public/favicon.ico +0 -0
  207. data/guides/code/getting_started/public/robots.txt +0 -5
  208. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
  209. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
  210. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
  211. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  212. data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
  213. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
  214. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
  215. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
  216. data/guides/code/getting_started/test/models/comment_test.rb +0 -7
  217. data/guides/code/getting_started/test/models/post_test.rb +0 -7
  218. data/guides/code/getting_started/test/test_helper.rb +0 -12
  219. data/guides/rails_guides/generator.rb +0 -248
  220. data/guides/rails_guides/helpers.rb +0 -53
  221. data/guides/rails_guides/indexer.rb +0 -68
  222. data/guides/rails_guides/kindle.rb +0 -119
  223. data/guides/rails_guides/levenshtein.rb +0 -31
  224. data/guides/rails_guides/markdown/renderer.rb +0 -82
  225. data/guides/rails_guides/markdown.rb +0 -163
  226. data/guides/rails_guides.rb +0 -63
  227. data/guides/source/2_2_release_notes.md +0 -435
  228. data/guides/source/2_3_release_notes.md +0 -621
  229. data/guides/source/3_0_release_notes.md +0 -611
  230. data/guides/source/3_1_release_notes.md +0 -556
  231. data/guides/source/3_2_release_notes.md +0 -565
  232. data/guides/source/4_0_release_notes.md +0 -276
  233. data/guides/source/4_1_release_notes.md +0 -731
  234. data/guides/source/_license.html.erb +0 -2
  235. data/guides/source/_welcome.html.erb +0 -25
  236. data/guides/source/action_controller_overview.md +0 -1175
  237. data/guides/source/action_mailer_basics.md +0 -689
  238. data/guides/source/action_view_overview.md +0 -1610
  239. data/guides/source/active_model_basics.md +0 -200
  240. data/guides/source/active_record_basics.md +0 -373
  241. data/guides/source/active_record_callbacks.md +0 -410
  242. data/guides/source/active_record_querying.md +0 -1773
  243. data/guides/source/active_record_validations.md +0 -1169
  244. data/guides/source/active_support_core_extensions.md +0 -3864
  245. data/guides/source/active_support_instrumentation.md +0 -496
  246. data/guides/source/api_documentation_guidelines.md +0 -315
  247. data/guides/source/asset_pipeline.md +0 -1163
  248. data/guides/source/association_basics.md +0 -2229
  249. data/guides/source/caching_with_rails.md +0 -354
  250. data/guides/source/command_line.md +0 -603
  251. data/guides/source/configuring.md +0 -942
  252. data/guides/source/contributing_to_ruby_on_rails.md +0 -544
  253. data/guides/source/credits.html.erb +0 -80
  254. data/guides/source/debugging_rails_applications.md +0 -707
  255. data/guides/source/development_dependencies_install.md +0 -278
  256. data/guides/source/documents.yaml +0 -193
  257. data/guides/source/engines.md +0 -1391
  258. data/guides/source/form_helpers.md +0 -1001
  259. data/guides/source/generators.md +0 -663
  260. data/guides/source/getting_started.md +0 -1947
  261. data/guides/source/i18n.md +0 -1043
  262. data/guides/source/index.html.erb +0 -27
  263. data/guides/source/initialization.md +0 -657
  264. data/guides/source/kindle/copyright.html.erb +0 -1
  265. data/guides/source/kindle/layout.html.erb +0 -27
  266. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  267. data/guides/source/kindle/toc.html.erb +0 -24
  268. data/guides/source/kindle/toc.ncx.erb +0 -64
  269. data/guides/source/kindle/welcome.html.erb +0 -5
  270. data/guides/source/layout.html.erb +0 -146
  271. data/guides/source/layouts_and_rendering.md +0 -1226
  272. data/guides/source/maintenance_policy.md +0 -56
  273. data/guides/source/migrations.md +0 -1109
  274. data/guides/source/nested_model_forms.md +0 -225
  275. data/guides/source/plugins.md +0 -444
  276. data/guides/source/rails_application_templates.md +0 -248
  277. data/guides/source/rails_on_rack.md +0 -333
  278. data/guides/source/routing.md +0 -1115
  279. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
  280. data/guides/source/security.md +0 -1018
  281. data/guides/source/testing.md +0 -1052
  282. data/guides/source/upgrading_ruby_on_rails.md +0 -899
  283. data/guides/source/working_with_javascript_in_rails.md +0 -405
  284. data/guides/w3c_validator.rb +0 -95
@@ -1,1773 +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 article_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 article_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 `joins` method would generate one using the `INNER JOIN` function instead.
1150
-
1151
- ```ruby
1152
- 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)
1153
- ```
1154
-
1155
- If there was no `where` condition, this would generate the normal set of two queries.
1156
-
1157
- If, in the case of this `includes` query, there were no comments for any posts, all the posts would still be loaded. By using `joins` (an INNER JOIN), the join conditions **must** match, otherwise no records will be returned.
1158
-
1159
- Scopes
1160
- ------
1161
-
1162
- 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.
1163
-
1164
- 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:
1165
-
1166
- ```ruby
1167
- class Post < ActiveRecord::Base
1168
- scope :published, -> { where(published: true) }
1169
- end
1170
- ```
1171
-
1172
- This is exactly the same as defining a class method, and which you use is a matter of personal preference:
1173
-
1174
- ```ruby
1175
- class Post < ActiveRecord::Base
1176
- def self.published
1177
- where(published: true)
1178
- end
1179
- end
1180
- ```
1181
-
1182
- Scopes are also chainable within scopes:
1183
-
1184
- ```ruby
1185
- class Post < ActiveRecord::Base
1186
- scope :published, -> { where(published: true) }
1187
- scope :published_and_commented, -> { published.where("comments_count > 0") }
1188
- end
1189
- ```
1190
-
1191
- To call this `published` scope we can call it on either the class:
1192
-
1193
- ```ruby
1194
- Post.published # => [published posts]
1195
- ```
1196
-
1197
- Or on an association consisting of `Post` objects:
1198
-
1199
- ```ruby
1200
- category = Category.first
1201
- category.posts.published # => [published posts belonging to this category]
1202
- ```
1203
-
1204
- ### Passing in arguments
1205
-
1206
- Your scope can take arguments:
1207
-
1208
- ```ruby
1209
- class Post < ActiveRecord::Base
1210
- scope :created_before, ->(time) { where("created_at < ?", time) }
1211
- end
1212
- ```
1213
-
1214
- Call the scope as if it were a class method:
1215
-
1216
- ```ruby
1217
- Post.created_before(Time.zone.now)
1218
- ```
1219
-
1220
- However, this is just duplicating the functionality that would be provided to you by a class method.
1221
-
1222
- ```ruby
1223
- class Post < ActiveRecord::Base
1224
- def self.created_before(time)
1225
- where("created_at < ?", time)
1226
- end
1227
- end
1228
- ```
1229
-
1230
- Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
1231
-
1232
- ```ruby
1233
- category.posts.created_before(time)
1234
- ```
1235
-
1236
- ### Merging of scopes
1237
-
1238
- Just like `where` clauses scopes are merged using `AND` conditions.
1239
-
1240
- ```ruby
1241
- class User < ActiveRecord::Base
1242
- scope :active, -> { where state: 'active' }
1243
- scope :inactive, -> { where state: 'inactive' }
1244
- end
1245
-
1246
- User.active.inactive
1247
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive'
1248
- ```
1249
-
1250
- We can mix and match `scope` and `where` conditions and the final sql
1251
- will have all conditions joined with `AND`.
1252
-
1253
- ```ruby
1254
- User.active.where(state: 'finished')
1255
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'finished'
1256
- ```
1257
-
1258
- If we do want the `last where clause` to win then `Relation#merge` can
1259
- be used.
1260
-
1261
- ```ruby
1262
- User.active.merge(User.inactive)
1263
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
1264
- ```
1265
-
1266
- One important caveat is that `default_scope` will be prepended in
1267
- `scope` and `where` conditions.
1268
-
1269
- ```ruby
1270
- class User < ActiveRecord::Base
1271
- default_scope { where state: 'pending' }
1272
- scope :active, -> { where state: 'active' }
1273
- scope :inactive, -> { where state: 'inactive' }
1274
- end
1275
-
1276
- User.all
1277
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
1278
-
1279
- User.active
1280
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'
1281
-
1282
- User.where(state: 'inactive')
1283
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
1284
- ```
1285
-
1286
- As you can see above the `default_scope` is being merged in both
1287
- `scope` and `where` conditions.
1288
-
1289
-
1290
- ### Applying a default scope
1291
-
1292
- If we wish for a scope to be applied across all queries to the model we can use the
1293
- `default_scope` method within the model itself.
1294
-
1295
- ```ruby
1296
- class Client < ActiveRecord::Base
1297
- default_scope { where("removed_at IS NULL") }
1298
- end
1299
- ```
1300
-
1301
- When queries are executed on this model, the SQL query will now look something like
1302
- this:
1303
-
1304
- ```sql
1305
- SELECT * FROM clients WHERE removed_at IS NULL
1306
- ```
1307
-
1308
- If you need to do more complex things with a default scope, you can alternatively
1309
- define it as a class method:
1310
-
1311
- ```ruby
1312
- class Client < ActiveRecord::Base
1313
- def self.default_scope
1314
- # Should return an ActiveRecord::Relation.
1315
- end
1316
- end
1317
- ```
1318
-
1319
- ### Removing All Scoping
1320
-
1321
- If we wish to remove scoping for any reason we can use the `unscoped` method. This is
1322
- especially useful if a `default_scope` is specified in the model and should not be
1323
- applied for this particular query.
1324
-
1325
- ```ruby
1326
- Client.unscoped.load
1327
- ```
1328
-
1329
- This method removes all scoping and will do a normal query on the table.
1330
-
1331
- Note that chaining `unscoped` with a `scope` does not work. In these cases, it is
1332
- recommended that you use the block form of `unscoped`:
1333
-
1334
- ```ruby
1335
- Client.unscoped {
1336
- Client.created_before(Time.zone.now)
1337
- }
1338
- ```
1339
-
1340
- Dynamic Finders
1341
- ---------------
1342
-
1343
- 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.
1344
-
1345
- 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")`
1346
-
1347
- 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)`.
1348
-
1349
- Find or Build a New Object
1350
- --------------------------
1351
-
1352
- NOTE: Some dynamic finders have been deprecated in Rails 4.0 and will be
1353
- removed in Rails 4.1. The best practice is to use Active Record scopes
1354
- instead. You can find the deprecation gem at
1355
- https://github.com/rails/activerecord-deprecated_finders
1356
-
1357
- 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.
1358
-
1359
- ### `find_or_create_by`
1360
-
1361
- 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.
1362
-
1363
- Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:
1364
-
1365
- ```ruby
1366
- Client.find_or_create_by(first_name: 'Andy')
1367
- # => #<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">
1368
- ```
1369
-
1370
- The SQL generated by this method looks like this:
1371
-
1372
- ```sql
1373
- SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
1374
- BEGIN
1375
- 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')
1376
- COMMIT
1377
- ```
1378
-
1379
- `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.
1380
-
1381
- The new record might not be saved to the database; that depends on whether validations passed or not (just like `create`).
1382
-
1383
- Suppose we want to set the 'locked' attribute to `false` if we're
1384
- creating a new record, but we don't want to include it in the query. So
1385
- we want to find the client named "Andy", or if that client doesn't
1386
- exist, create a client named "Andy" which is not locked.
1387
-
1388
- We can achieve this in two ways. The first is to use `create_with`:
1389
-
1390
- ```ruby
1391
- Client.create_with(locked: false).find_or_create_by(first_name: 'Andy')
1392
- ```
1393
-
1394
- The second way is using a block:
1395
-
1396
- ```ruby
1397
- Client.find_or_create_by(first_name: 'Andy') do |c|
1398
- c.locked = false
1399
- end
1400
- ```
1401
-
1402
- The block will only be executed if the client is being created. The
1403
- second time we run this code, the block will be ignored.
1404
-
1405
- ### `find_or_create_by!`
1406
-
1407
- 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
1408
-
1409
- ```ruby
1410
- validates :orders_count, presence: true
1411
- ```
1412
-
1413
- 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:
1414
-
1415
- ```ruby
1416
- Client.find_or_create_by!(first_name: 'Andy')
1417
- # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
1418
- ```
1419
-
1420
- ### `find_or_initialize_by`
1421
-
1422
- The `find_or_initialize_by` method will work just like
1423
- `find_or_create_by` but it will call `new` instead of `create`. This
1424
- means that a new model instance will be created in memory but won't be
1425
- saved to the database. Continuing with the `find_or_create_by` example, we
1426
- now want the client named 'Nick':
1427
-
1428
- ```ruby
1429
- nick = Client.find_or_initialize_by(first_name: 'Nick')
1430
- # => <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">
1431
-
1432
- nick.persisted?
1433
- # => false
1434
-
1435
- nick.new_record?
1436
- # => true
1437
- ```
1438
-
1439
- Because the object is not yet stored in the database, the SQL generated looks like this:
1440
-
1441
- ```sql
1442
- SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
1443
- ```
1444
-
1445
- When you want to save it to the database, just call `save`:
1446
-
1447
- ```ruby
1448
- nick.save
1449
- # => true
1450
- ```
1451
-
1452
- Finding by SQL
1453
- --------------
1454
-
1455
- 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:
1456
-
1457
- ```ruby
1458
- Client.find_by_sql("SELECT * FROM clients
1459
- INNER JOIN orders ON clients.id = orders.client_id
1460
- ORDER BY clients.created_at desc")
1461
- ```
1462
-
1463
- `find_by_sql` provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
1464
-
1465
- ### `select_all`
1466
-
1467
- `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.
1468
-
1469
- ```ruby
1470
- Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
1471
- ```
1472
-
1473
- ### `pluck`
1474
-
1475
- `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.
1476
-
1477
- ```ruby
1478
- Client.where(active: true).pluck(:id)
1479
- # SELECT id FROM clients WHERE active = 1
1480
- # => [1, 2, 3]
1481
-
1482
- Client.distinct.pluck(:role)
1483
- # SELECT DISTINCT role FROM clients
1484
- # => ['admin', 'member', 'guest']
1485
-
1486
- Client.pluck(:id, :name)
1487
- # SELECT clients.id, clients.name FROM clients
1488
- # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
1489
- ```
1490
-
1491
- `pluck` makes it possible to replace code like:
1492
-
1493
- ```ruby
1494
- Client.select(:id).map { |c| c.id }
1495
- # or
1496
- Client.select(:id).map(&:id)
1497
- # or
1498
- Client.select(:id, :name).map { |c| [c.id, c.name] }
1499
- ```
1500
-
1501
- with:
1502
-
1503
- ```ruby
1504
- Client.pluck(:id)
1505
- # or
1506
- Client.pluck(:id, :name)
1507
- ```
1508
-
1509
- Unlike `select`, `pluck` directly converts a database result into a Ruby `Array`,
1510
- without constructing `ActiveRecord` objects. This can mean better performance for
1511
- a large or often-running query. However, any model method overrides will
1512
- not be available. For example:
1513
-
1514
- ```ruby
1515
- class Client < ActiveRecord::Base
1516
- def name
1517
- "I am #{super}"
1518
- end
1519
- end
1520
-
1521
- Client.select(:name).map &:name
1522
- # => ["I am David", "I am Jeremy", "I am Jose"]
1523
-
1524
- Client.pluck(:name)
1525
- # => ["David", "Jeremy", "Jose"]
1526
- ```
1527
-
1528
- Furthermore, unlike `select` and other `Relation` scopes, `pluck` triggers an immediate
1529
- query, and thus cannot be chained with any further scopes, although it can work with
1530
- scopes already constructed earlier:
1531
-
1532
- ```ruby
1533
- Client.pluck(:name).limit(1)
1534
- # => NoMethodError: undefined method `limit' for #<Array:0x007ff34d3ad6d8>
1535
-
1536
- Client.limit(1).pluck(:name)
1537
- # => ["David"]
1538
- ```
1539
-
1540
- ### `ids`
1541
-
1542
- `ids` can be used to pluck all the IDs for the relation using the table's primary key.
1543
-
1544
- ```ruby
1545
- Person.ids
1546
- # SELECT id FROM people
1547
- ```
1548
-
1549
- ```ruby
1550
- class Person < ActiveRecord::Base
1551
- self.primary_key = "person_id"
1552
- end
1553
-
1554
- Person.ids
1555
- # SELECT person_id FROM people
1556
- ```
1557
-
1558
- Existence of Objects
1559
- --------------------
1560
-
1561
- If you simply want to check for the existence of the object there's a method called `exists?`.
1562
- This method will query the database using the same query as `find`, but instead of returning an
1563
- object or collection of objects it will return either `true` or `false`.
1564
-
1565
- ```ruby
1566
- Client.exists?(1)
1567
- ```
1568
-
1569
- The `exists?` method also takes multiple values, but the catch is that it will return `true` if any
1570
- one of those records exists.
1571
-
1572
- ```ruby
1573
- Client.exists?(id: [1,2,3])
1574
- # or
1575
- Client.exists?(name: ['John', 'Sergei'])
1576
- ```
1577
-
1578
- It's even possible to use `exists?` without any arguments on a model or a relation.
1579
-
1580
- ```ruby
1581
- Client.where(first_name: 'Ryan').exists?
1582
- ```
1583
-
1584
- The above returns `true` if there is at least one client with the `first_name` 'Ryan' and `false`
1585
- otherwise.
1586
-
1587
- ```ruby
1588
- Client.exists?
1589
- ```
1590
-
1591
- The above returns `false` if the `clients` table is empty and `true` otherwise.
1592
-
1593
- You can also use `any?` and `many?` to check for existence on a model or relation.
1594
-
1595
- ```ruby
1596
- # via a model
1597
- Post.any?
1598
- Post.many?
1599
-
1600
- # via a named scope
1601
- Post.recent.any?
1602
- Post.recent.many?
1603
-
1604
- # via a relation
1605
- Post.where(published: true).any?
1606
- Post.where(published: true).many?
1607
-
1608
- # via an association
1609
- Post.first.categories.any?
1610
- Post.first.categories.many?
1611
- ```
1612
-
1613
- Calculations
1614
- ------------
1615
-
1616
- This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
1617
-
1618
- All calculation methods work directly on a model:
1619
-
1620
- ```ruby
1621
- Client.count
1622
- # SELECT count(*) AS count_all FROM clients
1623
- ```
1624
-
1625
- Or on a relation:
1626
-
1627
- ```ruby
1628
- Client.where(first_name: 'Ryan').count
1629
- # SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
1630
- ```
1631
-
1632
- You can also use various finder methods on a relation for performing complex calculations:
1633
-
1634
- ```ruby
1635
- Client.includes("orders").where(first_name: 'Ryan', orders: { status: 'received' }).count
1636
- ```
1637
-
1638
- Which will execute:
1639
-
1640
- ```sql
1641
- SELECT count(DISTINCT clients.id) AS count_all FROM clients
1642
- LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
1643
- (clients.first_name = 'Ryan' AND orders.status = 'received')
1644
- ```
1645
-
1646
- ### Count
1647
-
1648
- 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)`.
1649
-
1650
- For options, please see the parent section, [Calculations](#calculations).
1651
-
1652
- ### Average
1653
-
1654
- 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:
1655
-
1656
- ```ruby
1657
- Client.average("orders_count")
1658
- ```
1659
-
1660
- This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
1661
-
1662
- For options, please see the parent section, [Calculations](#calculations).
1663
-
1664
- ### Minimum
1665
-
1666
- 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:
1667
-
1668
- ```ruby
1669
- Client.minimum("age")
1670
- ```
1671
-
1672
- For options, please see the parent section, [Calculations](#calculations).
1673
-
1674
- ### Maximum
1675
-
1676
- 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:
1677
-
1678
- ```ruby
1679
- Client.maximum("age")
1680
- ```
1681
-
1682
- For options, please see the parent section, [Calculations](#calculations).
1683
-
1684
- ### Sum
1685
-
1686
- 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:
1687
-
1688
- ```ruby
1689
- Client.sum("orders_count")
1690
- ```
1691
-
1692
- For options, please see the parent section, [Calculations](#calculations).
1693
-
1694
- Running EXPLAIN
1695
- ---------------
1696
-
1697
- You can run EXPLAIN on the queries triggered by relations. For example,
1698
-
1699
- ```ruby
1700
- User.where(id: 1).joins(:posts).explain
1701
- ```
1702
-
1703
- may yield
1704
-
1705
- ```
1706
- EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
1707
- +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
1708
- | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1709
- +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
1710
- | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
1711
- | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
1712
- +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
1713
- 2 rows in set (0.00 sec)
1714
- ```
1715
-
1716
- under MySQL.
1717
-
1718
- Active Record performs a pretty printing that emulates the one of the database
1719
- shells. So, the same query running with the PostgreSQL adapter would yield instead
1720
-
1721
- ```
1722
- EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "users"."id" = 1
1723
- QUERY PLAN
1724
- ------------------------------------------------------------------------------
1725
- Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
1726
- Join Filter: (posts.user_id = users.id)
1727
- -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
1728
- Index Cond: (id = 1)
1729
- -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
1730
- Filter: (posts.user_id = 1)
1731
- (6 rows)
1732
- ```
1733
-
1734
- Eager loading may trigger more than one query under the hood, and some queries
1735
- may need the results of previous ones. Because of that, `explain` actually
1736
- executes the query, and then asks for the query plans. For example,
1737
-
1738
- ```ruby
1739
- User.where(id: 1).includes(:posts).explain
1740
- ```
1741
-
1742
- yields
1743
-
1744
- ```
1745
- EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
1746
- +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1747
- | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1748
- +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1749
- | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
1750
- +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1751
- 1 row in set (0.00 sec)
1752
-
1753
- EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
1754
- +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1755
- | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1756
- +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1757
- | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
1758
- +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1759
- 1 row in set (0.00 sec)
1760
- ```
1761
-
1762
- under MySQL.
1763
-
1764
- ### Interpreting EXPLAIN
1765
-
1766
- Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
1767
- following pointers may be helpful:
1768
-
1769
- * SQLite3: [EXPLAIN QUERY PLAN](http://www.sqlite.org/eqp.html)
1770
-
1771
- * MySQL: [EXPLAIN Output Format](http://dev.mysql.com/doc/refman/5.6/en/explain-output.html)
1772
-
1773
- * PostgreSQL: [Using EXPLAIN](http://www.postgresql.org/docs/current/static/using-explain.html)