This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
active_record_querying.html
1315 lines (1198 loc) · 62 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 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: 액티브 레코드 쿼리 인터페이스</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>액티브 레코드 쿼리 인터페이스</h2>
<p>아 가이드는 액티브 레코드를 이용해서 데이터베이스에서 자료를 가지고 오는 다양한 방법을 다룹니다. 이 가이드를 익히면 여러분은 다음을 내용을 알 수 있습니다.:</p>
<ul>
<li>다양한 메소드와 조건을 이용해서 레코드 찾기</li>
<li>검색한 레코드의 순서 지정, 속성 가져오기, 그룹 짓기 그리고 다른 요소들</li>
<li>데이터 조회 쿼리 요청을 줄이기 위한 Eager Loading 사용</li>
<li>동적(Dynamic) finder 메소드 사용</li>
<li>특정 레코드의 존재여부 검사</li>
<li>액티브 레코드 모델에서 다양한 계산 수행</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">데이터베이스에서 객체 조회하기</a><ul><li><a href="#retrieving-multiple-objects">복수 객체 검색</a></li> <li><a href="#retrieving-multiple-objects-in-batches">일괄 작업(Batch)에서 여러 객체 검색하기</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></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></li><li><a href="#having">Having</a></li><li><a href="#overriding-conditions">Overriding Conditions</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="#using-a-string-sql-fragment">Using a String <span class="caps">SQL</span> Fragment</a></li> <li><a href="#using-array-hash-of-named-associations">Using Array/Hash of Named Associations</a></li> <li><a href="#specifying-conditions-on-the-joined-tables">Specifying Conditions on the Joined Tables</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="#working-with-times">Working with times</a></li> <li><a href="#passing-in-arguments">Passing in arguments</a></li></ul></li><li><a href="#dynamic-finders">Dynamic Finders</a></li><li><a href="#finding-by-sql">Finding by <span class="caps">SQL</span></a></li><li><a href="#select_all"><tt>select_all</tt></a></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="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class='warning'><p>이 가이드는 레일즈 3.0에 기초합니다. 기존 버전의 레일즈에서는 이 문서의 코드가 동작하지 않을 수 있습니다.</p></div>
<div class='warning'><p>이 가이드의 원본은 영문 버전인 <a href="http://guides.rubyonrails.org/active_record_querying.html">Active Record Query Interface</a> 입니다. 번역 과정에서 원본과 차이가 발생할 수 있습니다. 번역본은 원본의 참고로 생각해 주세요.</p></div>
<p>만약 여러분이 데이터베이스의 레코드를 찾기 위해 표준 SQL을 이용한다면, 일반적으로 여러분은 레일즈로 동일 작업에 대하여 더 좋은 방법을 알게 될 것입니다. 액티브 레코드는 <span class="caps">SQL</span> 사용이 필요한 많은 경우에서 여러분을 해방 시킵니다.</p>
<p>이 가이드의 코드 예제는 다음의 한가지 혹은 그 이상의 모델을 참고합니다.:</p>
<div class='info'><p>특별한 경우가 아니면, 아래의 모든 모델은 <tt>id</tt>를 기본키로 사용합니다.</p></div>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Client < ActiveRecord::Base
has_one :address
has_many :orders
has_and_belongs_to_many :roles
end
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Address < ActiveRecord::Base
belongs_to :client
end
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Order < ActiveRecord::Base
belongs_to :client, :counter_cache => true
end
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Role < ActiveRecord::Base
has_and_belongs_to_many :clients
end
</pre>
</div>
</notextile>
<p>액티브 레코드는 데이터베이스 상에서 쿼리를 실행하며 대부분의 데이터베이스와 호환됩니다. (MySQL, PostgresSQL, SQLite). 여러분이 사용하는 데이터베이스가 상이해도, 액티브 레코드 메소드 사용 방식은 항상 동일합니다.</p>
<h3 id="retrieving-objects-from-the-database">1 데이터베이스에서 객체 조회하기</h3>
<p>데이터베이스에서 객체를 조회하기 위해, 액티브 레코드는 몇가지 찾기(finder) 메소드를 제공합니다. 각 찾기 메소드는 기본 SQL을 사용하지 않고, 데이터베이스에 정확한 쿼리를 수행하기 위해서 인자를 받습니다.</p>
<p>메소드는 다음과 같습니다.:</p>
<ul>
<li><tt>where</tt></li>
<li><tt>select</tt></li>
<li><tt>group</tt></li>
<li><tt>order</tt></li>
<li><tt>limit</tt></li>
<li><tt>offset</tt></li>
<li><tt>joins</tt></li>
<li><tt>includes</tt></li>
<li><tt>lock</tt></li>
<li><tt>readonly</tt></li>
<li><tt>from</tt></li>
<li><tt>having</tt></li>
</ul>
<p>위의 모든 메소드는 <tt>ActiveRecord::Relation</tt>의 인스턴스를 반환합니다.</p>
<p><tt>Model.find(options)</tt>의 주요 동작은 다음으로 요약됩니다.:</p>
<ul>
<li>옵션을 동일 <span class="caps">SQL</span> 쿼리로 변환</li>
<li><span class="caps">SQL</span> 쿼리를 실행하고, 데이터베이스에서 관련 결과를 검색</li>
<li>모든 결과 열을 수용하는 적절한 루비 객체의 인스턴스를 생성</li>
<li><tt>after_find</tt> 콜백 실행</li>
</ul>
<h4 class="retrieving-a-single-object">단일 객체 검색</h4>
<p>액티브 레코드는 단일 객체 조회를 위해 3가지 다른 방법을 제공합니다.</p>
<h5 id="using-a-primary-key">기본키 이용하기</h5>
<p><tt>Model.find(primary_key)</tt>를 사용해서, 주어진 <em>기본키(primary key)</em>와 조건에 일치하는 객체를 찾을 수 있습니다. 예를들어:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# 기본키(id) 10 을 가지고 client 찾기
client = Client.find(10)
=> #<Client id: 10, first_name: => "Ryan">
</pre>
</div>
</notextile>
<p>위와 동일한 SQL은 다음과 같습니다.:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.id = 10)
</pre>
</div>
</notextile>
<p>만약 일치하는 레코드가 존재하지 않으면, <tt>Model.find(primary_key)</tt> 호출은 <tt>ActiveRecord::RecordNotFound</tt>을 발생시킵니다.</p>
<h5 id="first"><tt>first</tt></h5>
<p><tt>Model.first</tt>는 주어진 조건과 일치하는 첫번째 레코드를 찾습니다. 예를들어:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.first
=> #<Client id: 1, first_name: "Lifo">
</pre>
</div>
</notextile>
<p>위와 동일한 SQL은 다음과 같습니다.:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 1
</pre>
</div>
</notextile>
<p>만약 일치하는 레코드가 없다면, <tt>Model.first</tt>는 <tt>nil</tt>을 반환합니다. 예외가 발생하지는 않습니다.</p>
<h5 id="last"><tt>last</tt></h5>
<p><tt>Model.last</tt>는 주어진 조건과 일치하는 마지막 레코드를 찾습니다. 예를들어:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.last
=> #<Client id: 221, first_name: "Russel">
</pre>
</div>
</notextile>
<p>위와 동일한 SQL은 다음과 같습니다.:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
</pre>
</div>
</notextile>
<p>만약 일치하는 레코드가 없다면, <tt>Model.last</tt>는 <tt>nil</tt>을 반환합니다. 예외가 발생하지는 않습니다.</p>
<h4 id="retrieving-multiple-objects">1.1 복수 객체 검색</h4>
<h5 id="using-multiple-primary-keys">1.1.1 복수 기본키 사용하기</h5>
<p><tt>Model.find(array_of_primary_key)</tt>는 <tt>기본키(primary key)</tt>의 배열도 허용합니다. 주어진 <tt>여러 기본키</tt>와 일치하는 모든 레코드 배열이 반환됩니다. 예를들어:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# 기본키 1과 0에 해당하는 client 객체 찾기
client = Client.find(1, 10) # Or even Client.find([1, 10])
=> [#<Client id: 1, first_name: => "Lifo">, #<Client id: 10, first_name: => "Ryan">]
</pre>
</div>
</notextile>
<p>위와 동일한 SQL은 다음과 같습니다.:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients WHERE (clients.id IN (1,10))
</pre>
</div>
</notextile>
<div class='warning'><p><tt>Model.find(array_of_primary_key)</tt>는 입력된 여러 기본키 값들과 일치하는 레코드를 <strong>모두</strong> 찾을수 없다면 <tt>ActiveRecord::RecordNotFound</tt> 예외를 발생합니다. (한개라도 못찾으면 발생)</p></div>
<h4 id="retrieving-multiple-objects-in-batches">1.2 일괄 작업(Batch)에서 여러 객체 검색하기</h4>
<p>때로 많은 양의 레코드를 순회할 필요가 있습니다. 예를들어, 모든 사용자에게 뉴스레터를 보낼때나, 필요한 데이터를 빼낼때(export) 등 말이죠.</p>
<p>다음 코드는 아마도 맨 처음으로 곧바로 생각할 수 있는 방법일 겁니니다.:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# 열의 수가 수천개가 되는 사용자 테이블이라면 매우 비효율적입니다.
User.all.each do |user|
NewsLetter.weekly_deliver(user)
end
</pre>
</div>
</notextile>
<p>그러나 테이블의 전체 열의 수가 매우 크다면, 위의 접근 방식은 아마도
But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible.</p>
<p><tt>User.all.each</tt>는 액티브 레코드로 하여금 <em>전체 테이블</em> 정보를 가지고 오게 만들고, 각 행마다 모델 객체를 만들며 메모리에 전체 배열을 유지하게 하기 때문입니다. 때로는 너무 많은 객체를 만들고 굉장히 많은 매모리를 차지합니다.</p>
<h5 id="find_each">1.2.1 <tt>find_each</tt></h5>
<p>큰 테이블을 효율적으로 순회하기 위해서, 액티브 레코드는 <tt>find_each</tt>로 불리는 일괄 작업용 파인더 메소드를 제공합니다.:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each do |user|
NewsLetter.weekly_deliver(user)
end
</pre>
</div>
</notextile>
<p><strong>일괄 작업(batch) 크기 설정</strong></p>
<p><tt>find_each</tt>는 기본적으로 1000개 단위로 열을 가지고 와서 하나씩 블록을 실행합니다. 이 단위는 <tt>:batch_size</tt> 옵션을 통해서 설정할 수 있습니다.</p>
<p><tt>User</tt> 레코드를 <tt>5000</tt>개 단위로 가지고 와서 처리하려면:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each(:batch_size => 5000) do |user|
NewsLetter.weekly_deliver(user)
end
</pre>
</div>
</notextile>
<p><strong>정해진 기본키 부터 일괄 작업(batch) 조회 시작하기</strong></p>
<div class='warning'><p><tt>find_each</tt>는 레일즈 2.3.8까지만 존재하며, 이후 버전에서는 제거되었습니다. <tt>find_in_batches</tt>를 사용하세요.</p></div>
<p>레코드는 정수형 기본키에 의해 오름차순으로 불립니다. <tt>:start</tt> 옵션으로 최소 기본키를 설정할 수 있으며, 이 옵션은 이미 처리된 마지막 ID를 체크포인트 용도로 저장했다가, 다시 그 지점부터 일괄 작업을 재시작할때 유용하게 사용할 수 있습니다.</p>
<p>기본키 <tt>2000</tt> 이상의 사용자에게만 뉴스레터를 보내려면:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
User.find_each(:batch_size => 5000, :start => 2000) do |user|
NewsLetter.weekly_deliver(user)
end
</pre>
</div>
</notextile>
<p><strong>부가 옵션</strong></p>
<p><tt>find_each</tt>는 표준 <tt>find</tt> 메소드와 동일한 옵션을 허용합니다. 그렇지만 <tt>:order</tt>와 <tt>:limit</tt>는 내부적으로 필요해서 이 옵션들은 명시적으로 넘길수 없습니다.</p>
<h5 id="find_in_batches">1.2.2 <tt>find_in_batches</tt></h5>
<p>You can also work by chunks instead of row by row using <tt>find_in_batches</tt>. This method is analogous to <tt>find_each</tt>, but it yields arrays of models instead:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Works in chunks of 1000 invoices at a time.
Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
export.add_invoices(invoices)
end
</pre>
</div>
</notextile>
<p>The above will yield the supplied block with <tt>1000</tt> invoices every time.</p>
<h3 id="conditions">2 Conditions</h3>
<p>The <tt>find</tt> method allows you to specify conditions to limit the records returned, representing the <tt>WHERE</tt>-part of the <span class="caps">SQL</span> statement. Conditions can either be specified as a string, array, or hash.</p>
<h4 id="pure-string-conditions">2.1 Pure String Conditions</h4>
<p>If you’d like to add conditions to your find, you could just specify them in there, just like <tt>Client.where("orders_count = '2'")</tt>. This will find all clients where the <tt>orders_count</tt> field’s value is 2.</p>
<div class='warning'><p>Building your own conditions as pure strings can leave you vulnerable to <span class="caps">SQL</span> injection exploits. For example, <tt>Client.where("first_name LIKE '%#{params[:first_name]}%'")</tt> is not safe. See the next section for the preferred way to handle conditions using an array.</p></div>
<h4 id="array-conditions">2.2 Array Conditions</h4>
<p>Now what if that number could vary, say as an argument from somewhere? The find then becomes something like:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = ?", params[:orders])
</pre>
</div>
</notextile>
<p>Active Record will go through the first element in the conditions value and any additional elements will replace the question marks <tt>(?)</tt> in the first element.</p>
<p>Or if you want to specify two conditions, you can do it like:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = ? AND locked = ?", params[:orders], false)
</pre>
</div>
</notextile>
<p>In this example, the first question mark will be replaced with the value in <tt>params[:orders]</tt> and the second will be replaced with the <span class="caps">SQL</span> representation of <tt>false</tt>, which depends on the adapter.</p>
<p>The reason for doing code like:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = ?", params[:orders])
</pre>
</div>
</notextile>
<p>instead of:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where("orders_count = #{params[:orders]}")
</pre>
</div>
</notextile>
<p>is 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 he or she 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 <span class="caps">SQL</span> injection, see the <a href="security.html#sql-injection">Ruby on Rails Security Guide</a>.</p></div>
<h5 id="placeholder-conditions">2.2.1 Placeholder Conditions</h5>
<p>Similar to the <tt>(?)</tt> replacement style of params, you can also specify keys/values hash in your array conditions:</p>
<notextile>
<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>
</notextile>
<p>This makes for clearer readability if you have a large number of variable conditions.</p>
<h5 id="array-range_conditions">2.2.2 Range Conditions</h5>
<p>If you’re looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the <tt>IN</tt> <span class="caps">SQL</span> statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date))
</pre>
</div>
</notextile>
<p>This query will generate something similar to the following <span class="caps">SQL</span>:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30')
</pre>
</div>
</notextile>
<h4 id="hash-conditions">2.3 Hash Conditions</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 conditionalised and the values of how you want to conditionalise them:</p>
<div class='note'><p>Only equality, range and subset checking are possible with Hash conditions.</p></div>
<h5 id="equality-conditions">2.3.1 Equality Conditions</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(:locked => true)
</pre>
</div>
</notextile>
<p>The field name can also be a string:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where('locked' => true)
</pre>
</div>
</notextile>
<h5 id="hash-range_conditions">2.3.2 Range Conditions</h5>
<p>The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.</p>
<notextile>
<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>
</notextile>
<p>This will find all clients created yesterday by using a <tt>BETWEEN</tt> <span class="caps">SQL</span> statement:</p>
<notextile>
<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>
</notextile>
<p>This demonstrates a shorter syntax for the examples in <a href="#array-conditions">Array Conditions</a></p>
<h5 id="subset-conditions">2.3.3 Subset Conditions</h5>
<p>If you want to find records using the <tt>IN</tt> expression you can pass an array to the conditions hash:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.where(:orders_count => [1,3,5])
</pre>
</div>
</notextile>
<p>This code will generate <span class="caps">SQL</span> like this:</p>
<notextile>
<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>
</notextile>
<h3 id="ordering">3 Ordering</h3>
<p>To retrieve records from the database in a specific order, you can use the <tt>order</tt> method.</p>
<p>For example, if you’re getting a set of records and want to order them in ascending order by the <tt>created_at</tt> field in your table:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order("created_at")
</pre>
</div>
</notextile>
<p>You could specify <tt>ASC</tt> or <tt>DESC</tt> as well:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order("created_at DESC")
# OR
Client.order("created_at ASC")
</pre>
</div>
</notextile>
<p>Or ordering by multiple fields:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.order("orders_count ASC, created_at DESC")
</pre>
</div>
</notextile>
<h3 id="selecting-specific-fields">4 Selecting Specific Fields</h3>
<p>By default, <tt>Model.find</tt> selects all the fields from the result set using <tt>select *</tt>.</p>
<p>To select only a subset of fields from the result set, you can specify the subset via the <tt>select</tt> method.</p>
<div class='note'><p>If the <tt>select</tt> method is used, all the returning objects will be <a href="#readonly-objects">read only</a>.</p></div>
<p><br /></p>
<p>For example, to select only <tt>viewable_by</tt> and <tt>locked</tt> columns:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.select("viewable_by, locked")
</pre>
</div>
</notextile>
<p>The <span class="caps">SQL</span> query used by this find call will be somewhat like:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT viewable_by, locked FROM clients
</pre>
</div>
</notextile>
<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>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
ActiveRecord::MissingAttributeError: missing attribute: <attribute>
</pre>
</div>
</notextile>
<p>Where <tt><attribute></tt> is the attribute you asked for. The <tt>id</tt> method will not raise the <tt>ActiveRecord::MissingAttributeError</tt>, so just be careful when working with associations because they need the <tt>id</tt> method to function properly.</p>
<p>You can also call <span class="caps">SQL</span> functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the <tt>DISTINCT</tt> function you can do it like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.select("DISTINCT(name)")
</pre>
</div>
</notextile>
<h3 id="limit-and-offset">5 Limit and Offset</h3>
<p>To apply <tt>LIMIT</tt> to the <span class="caps">SQL</span> fired by the <tt>Model.find</tt>, you can specify the <tt>LIMIT</tt> using <tt>limit</tt> and <tt>offset</tt> methods on the relation.</p>
<p>You can use <tt>limit</tt> to specify the number of records to be retrieved, and use <tt>offset</tt> to specify the number of records to skip before starting to return the records. For example</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.limit(5)
</pre>
</div>
</notextile>
<p>will return a maximum of 5 clients and because it specifies no offset it will return the first 5 in the table. The <span class="caps">SQL</span> it executes looks like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 5
</pre>
</div>
</notextile>
<p>Adding <tt>offset</tt> to that</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.limit(5).offset(30)
</pre>
</div>
</notextile>
<p>will return instead a maximum of 5 clients beginning with the 31st. The <span class="caps">SQL</span> looks like:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 5, 30
</pre>
</div>
</notextile>
<h3 id="group">6 Group</h3>
<p>To apply a <tt>GROUP BY</tt> clause to the <span class="caps">SQL</span> fired by the finder, you can specify the <tt>group</tt> method on the find.</p>
<p>For example, if you want to find a collection of the dates orders were created on:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Order.group("date(created_at)").order("created_at")
</pre>
</div>
</notextile>
<p>And this will give you a single <tt>Order</tt> object for each date where there are orders in the database.</p>
<p>The <span class="caps">SQL</span> that would be executed would be something like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at
</pre>
</div>
</notextile>
<h3 id="having">7 Having</h3>
<p><span class="caps">SQL</span> uses the <tt>HAVING</tt> clause to specify conditions on the <tt>GROUP BY</tt> fields. You can add the <tt>HAVING</tt> clause to the <span class="caps">SQL</span> fired by the <tt>Model.find</tt> by adding the <tt>:having</tt> option to the find.</p>
<p>For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Order.group("date(created_at)").having("created_at > ?", 1.month.ago)
</pre>
</div>
</notextile>
<p>The <span class="caps">SQL</span> that would be executed would be something like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
</pre>
</div>
</notextile>
<p>This will return single order objects for each day, but only for the last month.</p>
<h3 id="overriding-conditions">8 Overriding Conditions</h3>
<p>You can specify certain conditions to be excepted by using the <tt>except</tt> method.</p>
<p>For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.where('id > 10').limit(20).order('id asc').except(:order)
</pre>
</div>
</notextile>
<p>The <span class="caps">SQL</span> that would be executed:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM posts WHERE id > 10 LIMIT 20
</pre>
</div>
</notextile>
<p>You can also override conditions using the <tt>only</tt> method.</p>
<p>For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
</pre>
</div>
</notextile>
<p>The <span class="caps">SQL</span> that would be executed:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
</pre>
</div>
</notextile>
<h3 id="readonly-objects">9 Readonly Objects</h3>
<p>Active Record provides <tt>readonly</tt> method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an <tt>ActiveRecord::ReadOnlyRecord</tt> exception.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
client = Client.readonly.first
client.visits += 1
client.save
</pre>
</div>
</notextile>
<p>As <tt>client</tt> is explicitly set to be a readonly object, the above code will raise an <tt>ActiveRecord::ReadOnlyRecord</tt> exception when calling <tt>client.save</tt> with an updated value of <em>visits</em>.</p>
<h3 id="locking-records-for-update">10 Locking Records for Update</h3>
<p>Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.</p>
<p>Active Record provides two locking mechanisms:</p>
<ul>
<li>Optimistic Locking</li>
<li>Pessimistic Locking</li>
</ul>
<h4 id="optimistic-locking">10.1 Optimistic Locking</h4>
<p>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 <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred and the update is ignored.</p>
<p><strong>Optimistic locking column</strong></p>
<p>In order to use optimistic locking, the table needs to have a column called <tt>lock_version</tt>. Each time the record is updated, Active Record increments the <tt>lock_version</tt> column. If an update request is made with a lower value in the <tt>lock_version</tt> field than is currently in the <tt>lock_version</tt> column in the database, the update request will fail with an <tt>ActiveRecord::StaleObjectError</tt>. Example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
c1 = Client.find(1)
c2 = Client.find(1)
c1.first_name = "Michael"
c1.save
c2.name = "should fail"
c2.save # Raises a ActiveRecord::StaleObjectError
</pre>
</div>
</notextile>
<p>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.</p>
<div class='note'><p>You must ensure that your database schema defaults the <tt>lock_version</tt> column to <tt>0</tt>.</p></div>
<p><br /></p>
<p>This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.</p>
<p>To override the name of the <tt>lock_version</tt> column, <tt>ActiveRecord::Base</tt> provides a class method called <tt>set_locking_column</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Client < ActiveRecord::Base
set_locking_column :lock_client_column
end
</pre>
</div>
</notextile>
<h4 id="pessimistic-locking">10.2 Pessimistic Locking</h4>
<p>Pessimistic locking uses a locking mechanism provided by the underlying database. Using <tt>lock</tt> when building a relation obtains an exclusive lock on the selected rows. Relations using <tt>lock</tt> are usually wrapped inside a transaction for preventing deadlock conditions.</p>
<p>For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Item.transaction do
i = Item.lock.first
i.name = 'Jones'
i.save
end
</pre>
</div>
</notextile>
<p>The above session produces the following <span class="caps">SQL</span> for a MySQL backend:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SQL (0.2ms) BEGIN
Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
SQL (0.8ms) COMMIT
</pre>
</div>
</notextile>
<p>You can also pass raw <span class="caps">SQL</span> to the <tt>lock</tt> method for allowing different types of locks. For example, MySQL has an expression called <tt>LOCK IN SHARE MODE</tt> 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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Item.transaction do
i = Item.lock("LOCK IN SHARE MODE").find(1)
i.increment!(:views)
end
</pre>
</div>
</notextile>
<h3 id="joining-tables">11 Joining Tables</h3>
<p>Active Record provides a finder method called <tt>joins</tt> for specifying <tt>JOIN</tt> clauses on the resulting <span class="caps">SQL</span>. There are multiple ways to use the <tt>joins</tt> method.</p>
<h4 id="using-a-string-sql-fragment">11.1 Using a String <span class="caps">SQL</span> Fragment</h4>
<p>You can just supply the raw <span class="caps">SQL</span> specifying the <tt>JOIN</tt> clause to <tt>joins</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
</pre>
</div>
</notextile>
<p>This will result in the following <span class="caps">SQL</span>:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
</pre>
</div>
</notextile>
<h4 id="using-array-hash-of-named-associations">11.2 Using Array/Hash of Named Associations</h4>
<div class='warning'><p>This method only works with <tt>INNER JOIN</tt>.</p></div>
<p>Active Record lets you use the names of the <a href="association_basics.html">associations</a> defined on the model as a shortcut for specifying <tt>JOIN</tt> clause for those associations when using the <tt>joins</tt> method.</p>
<p>For example, consider the following <tt>Category</tt>, <tt>Post</tt>, <tt>Comments</tt> and <tt>Guest</tt> models:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :category
has_many :comments
has_many :tags
end
class Comments < ActiveRecord::Base
belongs_to :post
has_one :guest
end
class Guest < ActiveRecord::Base
belongs_to :comment
end
</pre>
</div>
</notextile>
<p>Now all of the following will produce the expected join queries using <tt>INNER JOIN</tt>:</p>
<h5 id="joining-a-single-association">11.2.1 Joining a Single Association</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Category.joins(:posts)
</pre>
</div>
</notextile>
<p>This produces:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT categories.* FROM categories
INNER JOIN posts ON posts.category_id = categories.id
</pre>
</div>
</notextile>
<h5 id="joining-multiple-associations">11.2.2 Joining Multiple Associations</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.joins(:category, :comments)
</pre>
</div>
</notextile>
<p>This produces:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT posts.* FROM posts
INNER JOIN categories ON posts.category_id = categories.id
INNER JOIN comments ON comments.post_id = posts.id
</pre>
</div>
</notextile>
<h5 id="joining-nested-associations-single-level">11.2.3 Joining Nested Associations (Single Level)</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.joins(:comments => :guest)
</pre>
</div>
</notextile>
<h5 id="joining-nested-associations-multiple-level">11.2.4 Joining Nested Associations (Multiple Level)</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Category.joins(:posts => [{:comments => :guest}, :tags])
</pre>
</div>
</notextile>
<h4 id="specifying-conditions-on-the-joined-tables">11.3 Specifying Conditions on the Joined Tables</h4>
<p>You can specify conditions on the joined tables using the regular <a href="#array-conditions">Array</a> and <a href="#pure-string-conditions">String</a> conditions. <a href="#hash-conditions">Hash conditions</a> provides a special syntax for specifying conditions for the joined tables:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Client.joins(:orders).where('orders.created_at' => time_range)
</pre>
</div>
</notextile>
<p>An alternative and cleaner syntax is to nest the hash conditions:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Client.joins(:orders).where(:orders => {:created_at => time_range})
</pre>
</div>
</notextile>
<p>This will find all clients who have orders that were created yesterday, again using a <tt>BETWEEN</tt> <span class="caps">SQL</span> expression.</p>
<h3 id="eager-loading-associations">12 Eager Loading Associations</h3>
<p>Eager loading is the mechanism for loading the associated records of the objects returned by <tt>Model.find</tt> using as few queries as possible.</p>
<p><strong>N + 1 queries problem</strong></p>
<p>Consider the following code, which finds 10 clients and prints their postcodes:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
end
</pre>
</div>
</notextile>
<p>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 ) = <strong>11</strong> queries in total.</p>
<p><strong>Solution to N + 1 queries problem</strong></p>
<p>Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the <tt>includes</tt> method of the <tt>Model.find</tt> call. With <tt>includes</tt>, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.</p>
<p>Revisiting the above case, we could rewrite <tt>Client.all</tt> to use eager load addresses:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
clients = Client.includes(:address).limit(10)
clients.each do |client|
puts client.address.postcode
end
</pre>
</div>
</notextile>
<p>The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
</pre>
</div>
</notextile>
<h4 id="eager-loading-multiple-associations">12.1 Eager Loading Multiple Associations</h4>
<p>Active Record lets you eager load any number of associations with a single <tt>Model.find</tt> call by using an array, hash, or a nested hash of array/hash with the <tt>includes</tt> method.</p>
<h5 id="array-of-multiple-associations">12.1.1 Array of Multiple Associations</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.includes(:category, :comments)
</pre>
</div>
</notextile>
<p>This loads all the posts and the associated category and comments for each post.</p>
<h5 id="nested-associations-hash">12.1.2 Nested Associations Hash</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Category.includes(:posts => [{:comments => :guest}, :tags]).find(1)
</pre>
</div>
</notextile>
<p>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.</p>
<h4 id="specifying-conditions-on-eager-loaded-associations">12.2 Specifying Conditions on Eager Loaded Associations</h4>
<p>Even though Active Record lets you specify conditions on the eager loaded associations just like <tt>joins</tt>, the recommended way is to use <a href="#joining-tables">joins</a> instead.</p>
<h3 id="scopes">13 Scopes</h3>
<p>Scoping allows you to specify commonly-used ARel 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 <tt>where</tt>, <tt>joins</tt> and <tt>includes</tt>. All scope methods will return an <tt>ActiveRecord::Relation</tt> object which will allow for further methods (such as other scopes) to be called on it.</p>
<p>To define a simple scope, we use the <tt>scope</tt> method inside the class, passing the ARel query that we’d like run when this scope is called:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Post < ActiveRecord::Base
scope :published, where(:published => true)
end
</pre>
</div>
</notextile>
<p>Just like before, these methods are also chainable:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Post < ActiveRecord::Base
scope :published, where(:published => true).joins(:category)
end
</pre>
</div>
</notextile>
<p>Scopes are also chainable within scopes:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Post < ActiveRecord::Base
scope :published, where(:published => true)
scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
end
</pre>