-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactive_record_querying.html
2067 lines (1812 loc) · 113 KB
/
active_record_querying.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Active Record Query Interface — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Active Record Query Interface — Ruby on Rails Guides" />
<meta name="description" content="Active Record Query InterfaceThis guide covers different ways to retrieve data from the database using Active Record.After reading this guide, you will know: How to find records using a variety of methods and conditions. How to specify the order, retrieved attributes, grouping, and other properties of the found records. How to use eager loading to reduce the number of database queries needed for data retrieval. How to use dynamic finder methods. How to use method chaining to use multiple Active Record methods together. How to check for the existence of particular records. How to perform various calculations on Active Record models. How to run EXPLAIN on relations." />
<meta property="og:description" content="Active Record Query InterfaceThis guide covers different ways to retrieve data from the database using Active Record.After reading this guide, you will know: How to find records using a variety of methods and conditions. How to specify the order, retrieved attributes, grouping, and other properties of the found records. How to use eager loading to reduce the number of database queries needed for data retrieval. How to use dynamic finder methods. How to use method chaining to use multiple Active Record methods together. How to check for the existence of particular records. How to perform various calculations on Active Record models. How to run EXPLAIN on relations." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Active Record Query Interface</h2><p>This guide covers different ways to retrieve data from the database using Active Record.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to find records using a variety of methods and conditions.</li>
<li>How to specify the order, retrieved attributes, grouping, and other properties of the found records.</li>
<li>How to use eager loading to reduce the number of database queries needed for data retrieval.</li>
<li>How to use dynamic finder methods.</li>
<li>How to use method chaining to use multiple Active Record methods together.</li>
<li>How to check for the existence of particular records.</li>
<li>How to perform various calculations on Active Record models.</li>
<li>How to run EXPLAIN on relations.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li>
<a href="#retrieving-objects-from-the-database">Retrieving Objects from the Database</a>
<ul>
<li><a href="#retrieving-a-single-object">Retrieving a Single Object</a></li>
<li><a href="#retrieving-multiple-objects-in-batches">Retrieving Multiple Objects in Batches</a></li>
</ul>
</li>
<li>
<a href="#conditions">Conditions</a>
<ul>
<li><a href="#pure-string-conditions">Pure String Conditions</a></li>
<li><a href="#array-conditions">Array Conditions</a></li>
<li><a href="#hash-conditions">Hash Conditions</a></li>
<li><a href="#not-conditions">NOT Conditions</a></li>
<li><a href="#or-conditions">OR Conditions</a></li>
</ul>
</li>
<li><a href="#ordering">Ordering</a></li>
<li><a href="#selecting-specific-fields">Selecting Specific Fields</a></li>
<li><a href="#limit-and-offset">Limit and Offset</a></li>
<li>
<a href="#group">Group</a>
<ul>
<li><a href="#total-of-grouped-items">Total of grouped items</a></li>
</ul>
</li>
<li><a href="#having">Having</a></li>
<li>
<a href="#overriding-conditions">Overriding Conditions</a>
<ul>
<li><a href="#unscope"><code>unscope</code></a></li>
<li><a href="#only"><code>only</code></a></li>
<li><a href="#reselect"><code>reselect</code></a></li>
<li><a href="#reorder"><code>reorder</code></a></li>
<li><a href="#reverse-order"><code>reverse_order</code></a></li>
<li><a href="#rewhere"><code>rewhere</code></a></li>
</ul>
</li>
<li><a href="#null-relation">Null Relation</a></li>
<li><a href="#readonly-objects">Readonly Objects</a></li>
<li>
<a href="#locking-records-for-update">Locking Records for Update</a>
<ul>
<li><a href="#optimistic-locking">Optimistic Locking</a></li>
<li><a href="#pessimistic-locking">Pessimistic Locking</a></li>
</ul>
</li>
<li>
<a href="#joining-tables">Joining Tables</a>
<ul>
<li><a href="#joins"><code>joins</code></a></li>
<li><a href="#left-outer-joins"><code>left_outer_joins</code></a></li>
</ul>
</li>
<li>
<a href="#eager-loading-associations">Eager Loading Associations</a>
<ul>
<li><a href="#eager-loading-multiple-associations">Eager Loading Multiple Associations</a></li>
<li><a href="#specifying-conditions-on-eager-loaded-associations">Specifying Conditions on Eager Loaded Associations</a></li>
</ul>
</li>
<li>
<a href="#scopes">Scopes</a>
<ul>
<li><a href="#passing-in-arguments">Passing in arguments</a></li>
<li><a href="#using-conditionals">Using conditionals</a></li>
<li><a href="#applying-a-default-scope">Applying a default scope</a></li>
<li><a href="#merging-of-scopes">Merging of scopes</a></li>
<li><a href="#removing-all-scoping">Removing All Scoping</a></li>
</ul>
</li>
<li><a href="#dynamic-finders">Dynamic Finders</a></li>
<li><a href="#enums">Enums</a></li>
<li>
<a href="#understanding-the-method-chaining">Understanding The Method Chaining</a>
<ul>
<li><a href="#retrieving-filtered-data-from-multiple-tables">Retrieving filtered data from multiple tables</a></li>
<li><a href="#retrieving-specific-data-from-multiple-tables">Retrieving specific data from multiple tables</a></li>
</ul>
</li>
<li>
<a href="#find-or-build-a-new-object">Find or Build a New Object</a>
<ul>
<li><a href="#find-or-create-by"><code>find_or_create_by</code></a></li>
<li><a href="#find-or-create-by-bang"><code>find_or_create_by!</code></a></li>
<li><a href="#find-or-initialize-by"><code>find_or_initialize_by</code></a></li>
</ul>
</li>
<li>
<a href="#finding-by-sql">Finding by SQL</a>
<ul>
<li><a href="#select-all"><code>select_all</code></a></li>
<li><a href="#pluck"><code>pluck</code></a></li>
<li><a href="#ids"><code>ids</code></a></li>
</ul>
</li>
<li><a href="#existence-of-objects">Existence of Objects</a></li>
<li>
<a href="#calculations">Calculations</a>
<ul>
<li><a href="#count">Count</a></li>
<li><a href="#average">Average</a></li>
<li><a href="#minimum">Minimum</a></li>
<li><a href="#maximum">Maximum</a></li>
<li><a href="#sum">Sum</a></li>
</ul>
</li>
<li>
<a href="#running-explain">Running EXPLAIN</a>
<ul>
<li><a href="#interpreting-explain">Interpreting EXPLAIN</a></li>
</ul>
</li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<p>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.</p><p>Code examples throughout this guide will refer to one or more of the following models:</p><div class="info"><p>All of the following models use <code>id</code> as the primary key, unless specified otherwise.</p></div><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Client < ApplicationRecord
has_one :address
has_many :orders
has_and_belongs_to_many :roles
end
</pre>
</div>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Address < ApplicationRecord
belongs_to :client
end
</pre>
</div>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Order < ApplicationRecord
belongs_to :client, counter_cache: true
end
</pre>
</div>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Role < ApplicationRecord
has_and_belongs_to_many :clients
end
</pre>
</div>
<p>Active Record will perform queries on the database for you and is compatible with most database systems, including MySQL, MariaDB, PostgreSQL, and SQLite. Regardless of which database system you're using, the Active Record method format will always be the same.</p><h3 id="retrieving-objects-from-the-database"><a class="anchorlink" href="#retrieving-objects-from-the-database">1 Retrieving Objects from the Database</a></h3><p>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.</p><p>The methods are:</p>
<ul>
<li><code>annotate</code></li>
<li><code>find</code></li>
<li><code>create_with</code></li>
<li><code>distinct</code></li>
<li><code>eager_load</code></li>
<li><code>extending</code></li>
<li><code>extract_associated</code></li>
<li><code>from</code></li>
<li><code>group</code></li>
<li><code>having</code></li>
<li><code>includes</code></li>
<li><code>joins</code></li>
<li><code>left_outer_joins</code></li>
<li><code>limit</code></li>
<li><code>lock</code></li>
<li><code>none</code></li>
<li><code>offset</code></li>
<li><code>optimizer_hints</code></li>
<li><code>order</code></li>
<li><code>preload</code></li>
<li><code>readonly</code></li>
<li><code>references</code></li>
<li><code>reorder</code></li>
<li><code>reselect</code></li>
<li><code>reverse_order</code></li>
<li><code>select</code></li>
<li><code>where</code></li>
</ul>
<p>Finder methods that return a collection, such as <code>where</code> and <code>group</code>, return an instance of <code>ActiveRecord::Relation</code>. Methods that find a single entity, such as <code>find</code> and <code>first</code>, return a single instance of the model.</p><p>The primary operation of <code>Model.find(options)</code> can be summarized as:</p>
<ul>
<li>Convert the supplied options to an equivalent SQL query.</li>
<li>Fire the SQL query and retrieve the corresponding results from the database.</li>
<li>Instantiate the equivalent Ruby object of the appropriate model for every resulting row.</li>
<li>Run <code>after_find</code> and then <code>after_initialize</code> callbacks, if any.</li>
</ul>
<h4 id="retrieving-a-single-object"><a class="anchorlink" href="#retrieving-a-single-object">1.1 Retrieving a Single Object</a></h4><p>Active Record provides several different ways of retrieving a single object.</p><h5 id="find"><a class="anchorlink" href="#find">1.1.1 <code>find</code></a></h5><p>Using the <code>find</code> method, you can retrieve the object corresponding to the specified <em>primary key</em> that matches any supplied options. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Find the client with primary key (id) 10.
client = Client.find(10)
# => #<Client id: 10, first_name: "Ryan">
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
</pre>
</div>
<p>The <code>find</code> method will raise an <code>ActiveRecord::RecordNotFound</code> exception if no matching record is found.</p><p>You can also use this method to query for multiple objects. Call the <code>find</code> method and pass in an array of primary keys. The return will be an array containing all of the matching records for the supplied <em>primary keys</em>. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Find the clients with primary keys 1 and 10.
clients = Client.find([1, 10]) # Or even Client.find(1, 10)
# => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.id IN (1,10))
</pre>
</div>
<div class="warning"><p>The <code>find</code> method will raise an <code>ActiveRecord::RecordNotFound</code> exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.</p></div><h5 id="take"><a class="anchorlink" href="#take">1.1.2 <code>take</code></a></h5><p>The <code>take</code> method retrieves a record without any implicit ordering. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.take
# => #<Client id: 1, first_name: "Lifo">
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 1
</pre>
</div>
<p>The <code>take</code> method returns <code>nil</code> if no record is found and no exception will be raised.</p><p>You can pass in a numerical argument to the <code>take</code> method to return up to that number of results. For example</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
clients = Client.take(2)
# => [
# #<Client id: 1, first_name: "Lifo">,
# #<Client id: 220, first_name: "Sara">
# ]
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 2
</pre>
</div>
<p>The <code>take!</code> method behaves exactly like <code>take</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found.</p><div class="info"><p>The retrieved record may vary depending on the database engine.</p></div><h5 id="first"><a class="anchorlink" href="#first">1.1.3 <code>first</code></a></h5><p>The <code>first</code> method finds the first record ordered by primary key (default). For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.first
# => #<Client id: 1, first_name: "Lifo">
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
</pre>
</div>
<p>The <code>first</code> method returns <code>nil</code> if no matching record is found and no exception will be raised.</p><p>If your <a href="active_record_querying.html#applying-a-default-scope">default scope</a> contains an order method, <code>first</code> will return the first record according to this ordering.</p><p>You can pass in a numerical argument to the <code>first</code> method to return up to that number of results. For example</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
clients = Client.first(3)
# => [
# #<Client id: 1, first_name: "Lifo">,
# #<Client id: 2, first_name: "Fifo">,
# #<Client id: 3, first_name: "Filo">
# ]
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 3
</pre>
</div>
<p>On a collection that is ordered using <code>order</code>, <code>first</code> will return the first record ordered by the specified attribute for <code>order</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.order(:first_name).first
# => #<Client id: 2, first_name: "Fifo">
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.first_name ASC LIMIT 1
</pre>
</div>
<p>The <code>first!</code> method behaves exactly like <code>first</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found.</p><h5 id="last"><a class="anchorlink" href="#last">1.1.4 <code>last</code></a></h5><p>The <code>last</code> method finds the last record ordered by primary key (default). For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.last
# => #<Client id: 221, first_name: "Russel">
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
</pre>
</div>
<p>The <code>last</code> method returns <code>nil</code> if no matching record is found and no exception will be raised.</p><p>If your <a href="active_record_querying.html#applying-a-default-scope">default scope</a> contains an order method, <code>last</code> will return the last record according to this ordering.</p><p>You can pass in a numerical argument to the <code>last</code> method to return up to that number of results. For example</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
clients = Client.last(3)
# => [
# #<Client id: 219, first_name: "James">,
# #<Client id: 220, first_name: "Sara">,
# #<Client id: 221, first_name: "Russel">
# ]
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 3
</pre>
</div>
<p>On a collection that is ordered using <code>order</code>, <code>last</code> will return the last record ordered by the specified attribute for <code>order</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.order(:first_name).last
# => #<Client id: 220, first_name: "Sara">
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.first_name DESC LIMIT 1
</pre>
</div>
<p>The <code>last!</code> method behaves exactly like <code>last</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found.</p><h5 id="find-by"><a class="anchorlink" href="#find-by">1.1.5 <code>find_by</code></a></h5><p>The <code>find_by</code> method finds the first record matching some conditions. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.find_by first_name: 'Lifo'
# => #<Client id: 1, first_name: "Lifo">
Client.find_by first_name: 'Jon'
# => nil
</pre>
</div>
<p>It is equivalent to writing:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(first_name: 'Lifo').take
</pre>
</div>
<p>The SQL equivalent of the above is:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.first_name = 'Lifo') LIMIT 1
</pre>
</div>
<p>The <code>find_by!</code> method behaves exactly like <code>find_by</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.find_by! first_name: 'does not exist'
# => ActiveRecord::RecordNotFound
</pre>
</div>
<p>This is equivalent to writing:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(first_name: 'does not exist').take!
</pre>
</div>
<h4 id="retrieving-multiple-objects-in-batches"><a class="anchorlink" href="#retrieving-multiple-objects-in-batches">1.2 Retrieving Multiple Objects in Batches</a></h4><p>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.</p><p>This may appear straightforward:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# This may consume too much memory if the table is big.
User.all.each do |user|
NewsMailer.weekly(user).deliver_now
end
</pre>
</div>
<p>But this approach becomes increasingly impractical as the table size increases, since <code>User.all.each</code> instructs Active Record to fetch <em>the entire table</em> 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.</p><p>Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, <code>find_each</code>, retrieves a batch of records and then yields <em>each</em> record to the block individually as a model. The second method, <code>find_in_batches</code>, retrieves a batch of records and then yields <em>the entire batch</em> to the block as an array of models.</p><div class="info"><p>The <code>find_each</code> and <code>find_in_batches</code> 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.</p></div><h5 id="find-each"><a class="anchorlink" href="#find-each">1.2.1 <code>find_each</code></a></h5><p>The <code>find_each</code> method retrieves records in batches and then yields <em>each</em> one to the block. In the following example, <code>find_each</code> retrieves users in batches of 1000 and yields them to the block one by one:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each do |user|
NewsMailer.weekly(user).deliver_now
end
</pre>
</div>
<p>This process is repeated, fetching more batches as needed, until all of the records have been processed.</p><p><code>find_each</code> works on model classes, as seen above, and also on relations:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.where(weekly_subscriber: true).find_each do |user|
NewsMailer.weekly(user).deliver_now
end
</pre>
</div>
<p>as long as they have no ordering, since the method needs to force an order
internally to iterate.</p><p>If an order is present in the receiver the behaviour depends on the flag
<code>config.active_record.error_on_ignored_order</code>. If true, <code>ArgumentError</code> is
raised, otherwise the order is ignored and a warning issued, which is the
default. This can be overridden with the option <code>:error_on_ignore</code>, explained
below.</p><h6 id="options-for-find-each"><a class="anchorlink" href="#options-for-find-each">1.2.1.1 Options for <code>find_each</code></a></h6><p><strong><code>:batch_size</code></strong></p><p>The <code>:batch_size</code> 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:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each(batch_size: 5000) do |user|
NewsMailer.weekly(user).deliver_now
end
</pre>
</div>
<p><strong><code>:start</code></strong></p><p>By default, records are fetched in ascending order of the primary key. The <code>:start</code> 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.</p><p>For example, to send newsletters only to users with the primary key starting from 2000:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each(start: 2000) do |user|
NewsMailer.weekly(user).deliver_now
end
</pre>
</div>
<p><strong><code>:finish</code></strong></p><p>Similar to the <code>:start</code> option, <code>:finish</code> allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
This would be useful, for example, if you wanted to run a batch process using a subset of records based on <code>:start</code> and <code>:finish</code>.</p><p>For example, to send newsletters only to users with the primary key starting from 2000 up to 10000:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each(start: 2000, finish: 10000) do |user|
NewsMailer.weekly(user).deliver_now
end
</pre>
</div>
<p>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 <code>:start</code> and <code>:finish</code> options on each worker.</p><p><strong><code>:error_on_ignore</code></strong></p><p>Overrides the application config to specify if an error should be raised when an
order is present in the relation.</p><h5 id="find-in-batches"><a class="anchorlink" href="#find-in-batches">1.2.2 <code>find_in_batches</code></a></h5><p>The <code>find_in_batches</code> method is similar to <code>find_each</code>, since both retrieve batches of records. The difference is that <code>find_in_batches</code> yields <em>batches</em> 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:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Give add_invoices an array of 1000 invoices at a time.
Invoice.find_in_batches do |invoices|
export.add_invoices(invoices)
end
</pre>
</div>
<p><code>find_in_batches</code> works on model classes, as seen above, and also on relations:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Invoice.pending.find_in_batches do |invoices|
pending_invoices_export.add_invoices(invoices)
end
</pre>
</div>
<p>as long as they have no ordering, since the method needs to force an order
internally to iterate.</p><h6 id="options-for-find-in-batches"><a class="anchorlink" href="#options-for-find-in-batches">1.2.2.1 Options for <code>find_in_batches</code></a></h6><p>The <code>find_in_batches</code> method accepts the same options as <code>find_each</code>.</p><h3 id="conditions"><a class="anchorlink" href="#conditions">2 Conditions</a></h3><p>The <code>where</code> method allows you to specify conditions to limit the records returned, representing the <code>WHERE</code>-part of the SQL statement. Conditions can either be specified as a string, array, or hash.</p><h4 id="pure-string-conditions"><a class="anchorlink" href="#pure-string-conditions">2.1 Pure String Conditions</a></h4><p>If you'd like to add conditions to your find, you could just specify them in there, just like <code>Client.where("orders_count = '2'")</code>. This will find all clients where the <code>orders_count</code> field's value is 2.</p><div class="warning"><p>Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, <code>Client.where("first_name LIKE '%#{params[:first_name]}%'")</code> is not safe. See the next section for the preferred way to handle conditions using an array.</p></div><h4 id="array-conditions"><a class="anchorlink" href="#array-conditions">2.2 Array Conditions</a></h4><p>Now what if that number could vary, say as an argument from somewhere? The find would then take the form:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = ?", params[:orders])
</pre>
</div>
<p>Active Record will take the first argument as the conditions string and any additional arguments will replace the question marks <code>(?)</code> in it.</p><p>If you want to specify multiple conditions:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = ? AND locked = ?", params[:orders], false)
</pre>
</div>
<p>In this example, the first question mark will be replaced with the value in <code>params[:orders]</code> and the second will be replaced with the SQL representation of <code>false</code>, which depends on the adapter.</p><p>This code is highly preferable:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = ?", params[:orders])
</pre>
</div>
<p>to this code:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = #{params[:orders]}")
</pre>
</div>
<p>because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database <strong>as-is</strong>. 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.</p><div class="info"><p>For more information on the dangers of SQL injection, see the <a href="security.html#sql-injection">Ruby on Rails Security Guide</a>.</p></div><h5 id="placeholder-conditions"><a class="anchorlink" href="#placeholder-conditions">2.2.1 Placeholder Conditions</a></h5><p>Similar to the <code>(?)</code> replacement style of params, you can also specify keys in your conditions string along with a corresponding keys/values hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("created_at >= :start_date AND created_at <= :end_date",
{start_date: params[:start_date], end_date: params[:end_date]})
</pre>
</div>
<p>This makes for clearer readability if you have a large number of variable conditions.</p><h4 id="hash-conditions"><a class="anchorlink" href="#hash-conditions">2.3 Hash Conditions</a></h4><p>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 qualified and the values of how you want to qualify them:</p><div class="note"><p>Only equality, range, and subset checking are possible with Hash conditions.</p></div><h5 id="equality-conditions"><a class="anchorlink" href="#equality-conditions">2.3.1 Equality Conditions</a></h5><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(locked: true)
</pre>
</div>
<p>This will generate SQL like this:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.locked = 1)
</pre>
</div>
<p>The field name can also be a string:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where('locked' => true)
</pre>
</div>
<p>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.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.where(author: author)
Author.joins(:articles).where(articles: { author: author })
</pre>
</div>
<h5 id="range-conditions"><a class="anchorlink" href="#range-conditions">2.3.2 Range Conditions</a></h5><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
</pre>
</div>
<p>This will find all clients created yesterday by using a <code>BETWEEN</code> SQL statement:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
</pre>
</div>
<p>This demonstrates a shorter syntax for the examples in <a href="#array-conditions">Array Conditions</a></p><h5 id="subset-conditions"><a class="anchorlink" href="#subset-conditions">2.3.3 Subset Conditions</a></h5><p>If you want to find records using the <code>IN</code> expression you can pass an array to the conditions hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(orders_count: [1,3,5])
</pre>
</div>
<p>This code will generate SQL like this:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
</pre>
</div>
<h4 id="not-conditions"><a class="anchorlink" href="#not-conditions">2.4 NOT Conditions</a></h4><p><code>NOT</code> SQL queries can be built by <code>where.not</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where.not(locked: true)
</pre>
</div>
<p>In other words, this query can be generated by calling <code>where</code> with no argument, then immediately chain with <code>not</code> passing <code>where</code> conditions. This will generate SQL like this:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.locked != 1)
</pre>
</div>
<h4 id="or-conditions"><a class="anchorlink" href="#or-conditions">2.5 OR Conditions</a></h4><p><code>OR</code> conditions between two relations can be built by calling <code>or</code> on the first
relation, and passing the second one as an argument.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(locked: true).or(Client.where(orders_count: [1,3,5]))
</pre>
</div>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.locked = 1 OR clients.orders_count IN (1,3,5))
</pre>
</div>
<h3 id="ordering"><a class="anchorlink" href="#ordering">3 Ordering</a></h3><p>To retrieve records from the database in a specific order, you can use the <code>order</code> method.</p><p>For example, if you're getting a set of records and want to order them in ascending order by the <code>created_at</code> field in your table:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order(:created_at)
# OR
Client.order("created_at")
</pre>
</div>
<p>You could specify <code>ASC</code> or <code>DESC</code> as well:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order(created_at: :desc)
# OR
Client.order(created_at: :asc)
# OR
Client.order("created_at DESC")
# OR
Client.order("created_at ASC")
</pre>
</div>
<p>Or ordering by multiple fields:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order(orders_count: :asc, created_at: :desc)
# OR
Client.order(:orders_count, created_at: :desc)
# OR
Client.order("orders_count ASC, created_at DESC")
# OR
Client.order("orders_count ASC", "created_at DESC")
</pre>
</div>
<p>If you want to call <code>order</code> multiple times, subsequent orders will be appended to the first:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order("orders_count ASC").order("created_at DESC")
# SELECT * FROM clients ORDER BY orders_count ASC, created_at DESC
</pre>
</div>
<div class="warning"><p>In most database systems, on selecting fields with <code>distinct</code> from a result set using methods like <code>select</code>, <code>pluck</code> and <code>ids</code>; the <code>order</code> method will raise an <code>ActiveRecord::StatementInvalid</code> exception unless the field(s) used in <code>order</code> clause are included in the select list. See the next section for selecting fields from the result set.</p></div><h3 id="selecting-specific-fields"><a class="anchorlink" href="#selecting-specific-fields">4 Selecting Specific Fields</a></h3><p>By default, <code>Model.find</code> selects all the fields from the result set using <code>select *</code>.</p><p>To select only a subset of fields from the result set, you can specify the subset via the <code>select</code> method.</p><p>For example, to select only <code>viewable_by</code> and <code>locked</code> columns:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.select(:viewable_by, :locked)
# OR
Client.select("viewable_by, locked")
</pre>
</div>
<p>The SQL query used by this find call will be somewhat like:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT viewable_by, locked FROM clients
</pre>
</div>
<p>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:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
ActiveModel::MissingAttributeError: missing attribute: <attribute>
</pre>
</div>
<p>Where <code><attribute></code> is the attribute you asked for. The <code>id</code> method will not raise the <code>ActiveRecord::MissingAttributeError</code>, so just be careful when working with associations because they need the <code>id</code> method to function properly.</p><p>If you would like to only grab a single record per unique value in a certain field, you can use <code>distinct</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.select(:name).distinct
</pre>
</div>
<p>This would generate SQL like:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT DISTINCT name FROM clients
</pre>
</div>
<p>You can also remove the uniqueness constraint:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
query = Client.select(:name).distinct
# => Returns unique names
query.distinct(false)
# => Returns all names, even if there are duplicates
</pre>
</div>
<h3 id="limit-and-offset"><a class="anchorlink" href="#limit-and-offset">5 Limit and Offset</a></h3><p>To apply <code>LIMIT</code> to the SQL fired by the <code>Model.find</code>, you can specify the <code>LIMIT</code> using <code>limit</code> and <code>offset</code> methods on the relation.</p><p>You can use <code>limit</code> to specify the number of records to be retrieved, and use <code>offset</code> to specify the number of records to skip before starting to return the records. For example</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.limit(5)
</pre>
</div>
<p>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:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 5
</pre>
</div>
<p>Adding <code>offset</code> to that</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.limit(5).offset(30)
</pre>
</div>
<p>will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 5 OFFSET 30
</pre>
</div>
<h3 id="group"><a class="anchorlink" href="#group">6 Group</a></h3><p>To apply a <code>GROUP BY</code> clause to the SQL fired by the finder, you can use the <code>group</code> method.</p><p>For example, if you want to find a collection of the dates on which orders were created:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
</pre>
</div>
<p>And this will give you a single <code>Order</code> object for each date where there are orders in the database.</p><p>The SQL that would be executed would be something like this:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT date(created_at) as ordered_date, sum(price) as total_price
FROM orders
GROUP BY date(created_at)
</pre>
</div>
<h4 id="total-of-grouped-items"><a class="anchorlink" href="#total-of-grouped-items">6.1 Total of grouped items</a></h4><p>To get the total of grouped items on a single query, call <code>count</code> after the <code>group</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Order.group(:status).count
# => { 'awaiting_approval' => 7, 'paid' => 12 }
</pre>
</div>
<p>The SQL that would be executed would be something like this:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT COUNT (*) AS count_all, status AS status
FROM "orders"
GROUP BY status
</pre>
</div>
<h3 id="having"><a class="anchorlink" href="#having">7 Having</a></h3><p>SQL uses the <code>HAVING</code> clause to specify conditions on the <code>GROUP BY</code> fields. You can add the <code>HAVING</code> clause to the SQL fired by the <code>Model.find</code> by adding the <code>having</code> method to the find.</p><p>For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Order.select("date(created_at) as ordered_date, sum(price) as total_price").
group("date(created_at)").having("sum(price) > ?", 100)
</pre>
</div>
<p>The SQL that would be executed would be something like this:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT date(created_at) as ordered_date, sum(price) as total_price
FROM orders
GROUP BY date(created_at)
HAVING sum(price) > 100
</pre>
</div>
<p>This returns the date and total price for each order object, grouped by the day they were ordered and where the price is more than $100.</p><h3 id="overriding-conditions"><a class="anchorlink" href="#overriding-conditions">8 Overriding Conditions</a></h3><h4 id="unscope"><a class="anchorlink" href="#unscope">8.1 <code>unscope</code></a></h4><p>You can specify certain conditions to be removed using the <code>unscope</code> method. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.where('id > 10').limit(20).order('id asc').unscope(:order)
</pre>
</div>
<p>The SQL that would be executed:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM articles WHERE id > 10 LIMIT 20
# Original query without `unscope`
SELECT * FROM articles WHERE id > 10 ORDER BY id asc LIMIT 20
</pre>
</div>
<p>You can also unscope specific <code>where</code> clauses. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.where(id: 10, trashed: false).unscope(where: :id)
# SELECT "articles".* FROM "articles" WHERE trashed = 0
</pre>
</div>
<p>A relation which has used <code>unscope</code> will affect any relation into which it is merged:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.order('id asc').merge(Article.unscope(:order))
# SELECT "articles".* FROM "articles"
</pre>
</div>
<h4 id="only"><a class="anchorlink" href="#only">8.2 <code>only</code></a></h4><p>You can also override conditions using the <code>only</code> method. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.where('id > 10').limit(20).order('id desc').only(:order, :where)
</pre>
</div>
<p>The SQL that would be executed:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM articles WHERE id > 10 ORDER BY id DESC
# Original query without `only`
SELECT * FROM articles WHERE id > 10 ORDER BY id DESC LIMIT 20
</pre>
</div>
<h4 id="reselect"><a class="anchorlink" href="#reselect">8.3 <code>reselect</code></a></h4><p>The <code>reselect</code> method overrides an existing select statement. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.select(:title, :body).reselect(:created_at)
</pre>
</div>
<p>The SQL that would be executed:</p><div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT `posts`.`created_at` FROM `posts`
</pre>
</div>