-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactive_storage_overview.html
1025 lines (934 loc) · 49.3 KB
/
active_storage_overview.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 Storage Overview — 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 Storage Overview — Ruby on Rails Guides" />
<meta name="description" content="Active Storage OverviewThis guide covers how to attach files to your Active Record models.After reading this guide, you will know: How to attach one or many files to a record. How to delete an attached file. How to link to an attached file. How to use variants to transform images. How to generate an image representation of a non-image file, such as a PDF or a video. How to send file uploads directly from browsers to a storage service, bypassing your application servers. How to clean up files stored during testing. How to implement support for additional storage services." />
<meta property="og:description" content="Active Storage OverviewThis guide covers how to attach files to your Active Record models.After reading this guide, you will know: How to attach one or many files to a record. How to delete an attached file. How to link to an attached file. How to use variants to transform images. How to generate an image representation of a non-image file, such as a PDF or a video. How to send file uploads directly from browsers to a storage service, bypassing your application servers. How to clean up files stored during testing. How to implement support for additional storage services." />
<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 Storage Overview</h2><p>This guide covers how to attach files to your Active Record models.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to attach one or many files to a record.</li>
<li>How to delete an attached file.</li>
<li>How to link to an attached file.</li>
<li>How to use variants to transform images.</li>
<li>How to generate an image representation of a non-image file, such as a PDF or a video.</li>
<li>How to send file uploads directly from browsers to a storage service,
bypassing your application servers.</li>
<li>How to clean up files stored during testing.</li>
<li>How to implement support for additional storage services.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-is-active-storage-questionmark">What is Active Storage?</a></li>
<li>
<a href="#setup">Setup</a>
<ul>
<li><a href="#disk-service">Disk Service</a></li>
<li><a href="#amazon-s3-service">Amazon S3 Service</a></li>
<li><a href="#microsoft-azure-storage-service">Microsoft Azure Storage Service</a></li>
<li><a href="#google-cloud-storage-service">Google Cloud Storage Service</a></li>
<li><a href="#mirror-service">Mirror Service</a></li>
</ul>
</li>
<li>
<a href="#attaching-files-to-records">Attaching Files to Records</a>
<ul>
<li><a href="#has-one-attached"><code>has_one_attached</code></a></li>
<li><a href="#has-many-attached"><code>has_many_attached</code></a></li>
<li><a href="#attaching-file-io-objects">Attaching File/IO Objects</a></li>
</ul>
</li>
<li><a href="#removing-files">Removing Files</a></li>
<li><a href="#linking-to-files">Linking to Files</a></li>
<li><a href="#downloading-files">Downloading Files</a></li>
<li><a href="#transforming-images">Transforming Images</a></li>
<li><a href="#previewing-files">Previewing Files</a></li>
<li>
<a href="#direct-uploads">Direct Uploads</a>
<ul>
<li><a href="#direct-upload-installation">Direct upload installation</a></li>
<li><a href="#direct-upload-javascript-events">Direct upload JavaScript events</a></li>
<li><a href="#example">Example</a></li>
<li><a href="#integrating-with-libraries-or-frameworks">Integrating with Libraries or Frameworks</a></li>
</ul>
</li>
<li><a href="#discarding-files-stored-during-system-tests">Discarding Files Stored During System Tests</a></li>
<li><a href="#discarding-files-stored-during-integration-tests">Discarding Files Stored During Integration Tests</a></li>
<li><a href="#implementing-support-for-other-cloud-services">Implementing Support for Other Cloud Services</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-active-storage-questionmark"><a class="anchorlink" href="#what-is-active-storage-questionmark">1 What is Active Storage?</a></h3><p>Active Storage facilitates uploading files to a cloud storage service like
Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those
files to Active Record objects. It comes with a local disk-based service for
development and testing and supports mirroring files to subordinate services for
backups and migrations.</p><p>Using Active Storage, an application can transform image uploads with
<a href="https://www.imagemagick.org">ImageMagick</a>, generate image representations of
non-image uploads like PDFs and videos, and extract metadata from arbitrary
files.</p><h3 id="setup"><a class="anchorlink" href="#setup">2 Setup</a></h3><p>Active Storage uses two tables in your application’s database named
<code>active_storage_blobs</code> and <code>active_storage_attachments</code>. After creating a new
application (or upgrading your application to Rails 5.2), run
<code>rails active_storage:install</code> to generate a migration that creates these
tables. Use <code>rails db:migrate</code> to run the migration.</p><div class="warning"><p><code>active_storage_attachments</code> is a polymorphic join table that stores your model's class name. If your model's class name changes, you will need to run a migration on this table to update the underlying <code>record_type</code> to your model's new class name.</p></div><p>Declare Active Storage services in <code>config/storage.yml</code>. For each service your
application uses, provide a name and the requisite configuration. The example
below declares three services named <code>local</code>, <code>test</code>, and <code>amazon</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
local:
service: Disk
root: <%= Rails.root.join("storage") %>
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
amazon:
service: S3
access_key_id: ""
secret_access_key: ""
bucket: ""
region: "" # e.g. 'us-east-1'
</pre>
</div>
<p>Tell Active Storage which service to use by setting
<code>Rails.application.config.active_storage.service</code>. Because each environment will
likely use a different service, it is recommended to do this on a
per-environment basis. To use the disk service from the previous example in the
development environment, you would add the following to
<code>config/environments/development.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Store files locally.
config.active_storage.service = :local
</pre>
</div>
<p>To use the Amazon S3 service in production, you add the following to
<code>config/environments/production.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Store files on Amazon S3.
config.active_storage.service = :amazon
</pre>
</div>
<p>To use the test service when testing, you add the following to
<code>config/environments/test.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :test
</pre>
</div>
<p>Continue reading for more information on the built-in service adapters (e.g.
<code>Disk</code> and <code>S3</code>) and the configuration they require.</p><h4 id="disk-service"><a class="anchorlink" href="#disk-service">2.1 Disk Service</a></h4><p>Declare a Disk service in <code>config/storage.yml</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
local:
service: Disk
root: <%= Rails.root.join("storage") %>
</pre>
</div>
<h4 id="amazon-s3-service"><a class="anchorlink" href="#amazon-s3-service">2.2 Amazon S3 Service</a></h4><p>Declare an S3 service in <code>config/storage.yml</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
amazon:
service: S3
access_key_id: ""
secret_access_key: ""
region: ""
bucket: ""
</pre>
</div>
<p>Add the <a href="https://github.com/aws/aws-sdk-ruby"><code>aws-sdk-s3</code></a> gem to your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem "aws-sdk-s3", require: false
</pre>
</div>
<div class="note"><p>The core features of Active Storage require the following permissions: <code>s3:ListBucket</code>, <code>s3:PutObject</code>, <code>s3:GetObject</code>, and <code>s3:DeleteObject</code>. If you have additional upload options configured such as setting ACLs then additional permissions may be required.</p></div><div class="note"><p>If you want to use environment variables, standard SDK configuration files, profiles,
IAM instance profiles or task roles, you can omit the <code>access_key_id</code>, <code>secret_access_key</code>,
and <code>region</code> keys in the example above. The Amazon S3 Service supports all of the
authentication options described in the <a href="https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html">AWS SDK documentation</a>.</p></div><h4 id="microsoft-azure-storage-service"><a class="anchorlink" href="#microsoft-azure-storage-service">2.3 Microsoft Azure Storage Service</a></h4><p>Declare an Azure Storage service in <code>config/storage.yml</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
azure:
service: AzureStorage
storage_account_name: ""
storage_access_key: ""
container: ""
</pre>
</div>
<p>Add the <a href="https://github.com/Azure/azure-storage-ruby"><code>azure-storage</code></a> gem to your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem "azure-storage", require: false
</pre>
</div>
<h4 id="google-cloud-storage-service"><a class="anchorlink" href="#google-cloud-storage-service">2.4 Google Cloud Storage Service</a></h4><p>Declare a Google Cloud Storage service in <code>config/storage.yml</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
google:
service: GCS
credentials: <%= Rails.root.join("path/to/keyfile.json") %>
project: ""
bucket: ""
</pre>
</div>
<p>Optionally provide a Hash of credentials instead of a keyfile path:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
google:
service: GCS
credentials:
type: "service_account"
project_id: ""
private_key_id: <%= Rails.application.credentials.dig(:gcs, :private_key_id) %>
private_key: <%= Rails.application.credentials.dig(:gcs, :private_key).dump %>
client_email: ""
client_id: ""
auth_uri: "https://accounts.google.com/o/oauth2/auth"
token_uri: "https://accounts.google.com/o/oauth2/token"
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs"
client_x509_cert_url: ""
project: ""
bucket: ""
</pre>
</div>
<p>Add the <a href="https://github.com/GoogleCloudPlatform/google-cloud-ruby/tree/master/google-cloud-storage"><code>google-cloud-storage</code></a> gem to your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem "google-cloud-storage", "~> 1.11", require: false
</pre>
</div>
<h4 id="mirror-service"><a class="anchorlink" href="#mirror-service">2.5 Mirror Service</a></h4><p>You can keep multiple services in sync by defining a mirror service. When a file
is uploaded or deleted, it's done across all the mirrored services. Mirrored
services can be used to facilitate a migration between services in production.
You can start mirroring to the new service, copy existing files from the old
service to the new, then go all-in on the new service. Define each of the
services you'd like to use as described above and reference them from a mirrored
service.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
s3_west_coast:
service: S3
access_key_id: ""
secret_access_key: ""
region: ""
bucket: ""
s3_east_coast:
service: S3
access_key_id: ""
secret_access_key: ""
region: ""
bucket: ""
production:
service: Mirror
primary: s3_east_coast
mirrors:
- s3_west_coast
</pre>
</div>
<div class="note"><p>Files are served from the primary service.</p></div><div class="note"><p>This is not compatible with the <a href="#direct-uploads">direct uploads</a> feature.</p></div><h3 id="attaching-files-to-records"><a class="anchorlink" href="#attaching-files-to-records">3 Attaching Files to Records</a></h3><h4 id="has-one-attached"><a class="anchorlink" href="#has-one-attached">3.1 <code>has_one_attached</code></a></h4><p>The <code>has_one_attached</code> macro sets up a one-to-one mapping between records and
files. Each record can have one file attached to it.</p><p>For example, suppose your application has a <code>User</code> model. If you want each user to
have an avatar, define the <code>User</code> model like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
has_one_attached :avatar
end
</pre>
</div>
<p>You can create a user with an avatar:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form.file_field :avatar %>
</pre>
</div>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class SignupController < ApplicationController
def create
user = User.create!(user_params)
session[:user_id] = user.id
redirect_to root_path
end
private
def user_params
params.require(:user).permit(:email_address, :password, :avatar)
end
end
</pre>
</div>
<p>Call <code>avatar.attach</code> to attach an avatar to an existing user:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user.avatar.attach(params[:avatar])
</pre>
</div>
<p>Call <code>avatar.attached?</code> to determine whether a particular user has an avatar:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user.avatar.attached?
</pre>
</div>
<h4 id="has-many-attached"><a class="anchorlink" href="#has-many-attached">3.2 <code>has_many_attached</code></a></h4><p>The <code>has_many_attached</code> macro sets up a one-to-many relationship between records
and files. Each record can have many files attached to it.</p><p>For example, suppose your application has a <code>Message</code> model. If you want each
message to have many images, define the <code>Message</code> model like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Message < ApplicationRecord
has_many_attached :images
end
</pre>
</div>
<p>You can create a message with images:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class MessagesController < ApplicationController
def create
message = Message.create!(message_params)
redirect_to message
end
private
def message_params
params.require(:message).permit(:title, :content, images: [])
end
end
</pre>
</div>
<p>Call <code>images.attach</code> to add new images to an existing message:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@message.images.attach(params[:images])
</pre>
</div>
<p>Call <code>images.attached?</code> to determine whether a particular message has any images:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@message.images.attached?
</pre>
</div>
<h4 id="attaching-file-io-objects"><a class="anchorlink" href="#attaching-file-io-objects">3.3 Attaching File/IO Objects</a></h4><p>Sometimes you need to attach a file that doesn’t arrive via an HTTP request.
For example, you may want to attach a file you generated on disk or downloaded
from a user-submitted URL. You may also want to attach a fixture file in a
model test. To do that, provide a Hash containing at least an open IO object
and a filename:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf')
</pre>
</div>
<p>When possible, provide a content type as well. Active Storage attempts to
determine a file’s content type from its data. It falls back to the content
type you provide if it can’t do that.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf', content_type: 'application/pdf')
</pre>
</div>
<p>You can bypass the content type inference from the data by passing in
<code>identify: false</code> along with the <code>content_type</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@message.image.attach(
io: File.open('/path/to/file'),
filename: 'file.pdf',
content_type: 'application/pdf',
identify: false
)
</pre>
</div>
<p>If you don’t provide a content type and Active Storage can’t determine the
file’s content type automatically, it defaults to application/octet-stream.</p><h3 id="removing-files"><a class="anchorlink" href="#removing-files">4 Removing Files</a></h3><p>To remove an attachment from a model, call <code>purge</code> on the attachment. Removal
can be done in the background if your application is setup to use Active Job.
Purging deletes the blob and the file from the storage service.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Synchronously destroy the avatar and actual resource files.
user.avatar.purge
# Destroy the associated models and actual resource files async, via Active Job.
user.avatar.purge_later
</pre>
</div>
<h3 id="linking-to-files"><a class="anchorlink" href="#linking-to-files">5 Linking to Files</a></h3><p>Generate a permanent URL for the blob that points to the application. Upon
access, a redirect to the actual service endpoint is returned. This indirection
decouples the public URL from the actual one, and allows, for example, mirroring
attachments in different services for high-availability. The redirection has an
HTTP expiration of 5 min.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
url_for(user.avatar)
</pre>
</div>
<p>To create a download link, use the <code>rails_blob_{path|url}</code> helper. Using this
helper allows you to set the disposition.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
rails_blob_path(user.avatar, disposition: "attachment")
</pre>
</div>
<p>If you need to create a link from outside of controller/view context (Background
jobs, Cronjobs, etc.), you can access the rails_blob_path like this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
Rails.application.routes.url_helpers.rails_blob_path(user.avatar, only_path: true)
</pre>
</div>
<h3 id="downloading-files"><a class="anchorlink" href="#downloading-files">6 Downloading Files</a></h3><p>Sometimes you need to process a blob after it’s uploaded—for example, to convert
it to a different format. Use <code>ActiveStorage::Blob#download</code> to read a blob’s
binary data into memory:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
binary = user.avatar.download
</pre>
</div>
<p>You might want to download a blob to a file on disk so an external program (e.g.
a virus scanner or media transcoder) can operate on it. Use
<code>ActiveStorage::Blob#open</code> to download a blob to a tempfile on disk:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
message.video.open do |file|
system '/path/to/virus/scanner', file.path
# ...
end
</pre>
</div>
<h3 id="transforming-images"><a class="anchorlink" href="#transforming-images">7 Transforming Images</a></h3><p>To create a variation of the image, call <code>variant</code> on the <code>Blob</code>. You can pass
any transformation to the method supported by the processor. The default
processor is <a href="https://github.com/minimagick/minimagick">MiniMagick</a>, but you
can also use <a href="https://www.rubydoc.info/gems/ruby-vips/Vips/Image">Vips</a>.</p><p>To enable variants, add the <code>image_processing</code> gem to your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'image_processing', '~> 1.2'
</pre>
</div>
<p>When the browser hits the variant URL, Active Storage will lazily transform the
original blob into the specified format and redirect to its new service
location.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>
</pre>
</div>
<p>To switch to the Vips processor, you would add the following to
<code>config/application.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Use Vips for processing variants.
config.active_storage.variant_processor = :vips
</pre>
</div>
<h3 id="previewing-files"><a class="anchorlink" href="#previewing-files">8 Previewing Files</a></h3><p>Some non-image files can be previewed: that is, they can be presented as images.
For example, a video file can be previewed by extracting its first frame. Out of
the box, Active Storage supports previewing videos and PDF documents.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<ul>
<% @message.files.each do |file| %>
<li>
<%= image_tag file.preview(resize_to_limit: [100, 100]) %>
</li>
<% end %>
</ul>
</pre>
</div>
<div class="warning"><p>Extracting previews requires third-party applications, FFmpeg for
video and muPDF for PDFs, and on macOS also XQuartz and Poppler.
These libraries are not provided by Rails. You must install them yourself to
use the built-in previewers. Before you install and use third-party software,
make sure you understand the licensing implications of doing so.</p></div><h3 id="direct-uploads"><a class="anchorlink" href="#direct-uploads">9 Direct Uploads</a></h3><p>Active Storage, with its included JavaScript library, supports uploading
directly from the client to the cloud.</p><h4 id="direct-upload-installation"><a class="anchorlink" href="#direct-upload-installation">9.1 Direct upload installation</a></h4>
<ol>
<li>
<p>Include <code>activestorage.js</code> in your application's JavaScript bundle.</p>
<p>Using the asset pipeline:</p>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
//= require activestorage
</pre>
</div>
<p>Using the npm package:</p>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
require("@rails/activestorage").start()
</pre>
</div>
</li>
<li>
<p>Annotate file inputs with the direct upload URL.</p>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form.file_field :attachments, multiple: true, direct_upload: true %>
</pre>
</div>
</li>
<li><p>That's it! Uploads begin upon form submission.</p></li>
</ol>
<h4 id="direct-upload-javascript-events"><a class="anchorlink" href="#direct-upload-javascript-events">9.2 Direct upload JavaScript events</a></h4>
<table>
<thead>
<tr>
<th>Event name</th>
<th>Event target</th>
<th>Event data (<code>event.detail</code>)</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>direct-uploads:start</code></td>
<td><code><form></code></td>
<td>None</td>
<td>A form containing files for direct upload fields was submitted.</td>
</tr>
<tr>
<td><code>direct-upload:initialize</code></td>
<td><code><input></code></td>
<td><code>{id, file}</code></td>
<td>Dispatched for every file after form submission.</td>
</tr>
<tr>
<td><code>direct-upload:start</code></td>
<td><code><input></code></td>
<td><code>{id, file}</code></td>
<td>A direct upload is starting.</td>
</tr>
<tr>
<td><code>direct-upload:before-blob-request</code></td>
<td><code><input></code></td>
<td><code>{id, file, xhr}</code></td>
<td>Before making a request to your application for direct upload metadata.</td>
</tr>
<tr>
<td><code>direct-upload:before-storage-request</code></td>
<td><code><input></code></td>
<td><code>{id, file, xhr}</code></td>
<td>Before making a request to store a file.</td>
</tr>
<tr>
<td><code>direct-upload:progress</code></td>
<td><code><input></code></td>
<td><code>{id, file, progress}</code></td>
<td>As requests to store files progress.</td>
</tr>
<tr>
<td><code>direct-upload:error</code></td>
<td><code><input></code></td>
<td><code>{id, file, error}</code></td>
<td>An error occurred. An <code>alert</code> will display unless this event is canceled.</td>
</tr>
<tr>
<td><code>direct-upload:end</code></td>
<td><code><input></code></td>
<td><code>{id, file}</code></td>
<td>A direct upload has ended.</td>
</tr>
<tr>
<td><code>direct-uploads:end</code></td>
<td><code><form></code></td>
<td>None</td>
<td>All direct uploads have ended.</td>
</tr>
</tbody>
</table>
<h4 id="example"><a class="anchorlink" href="#example">9.3 Example</a></h4><p>You can use these events to show the progress of an upload.</p><p><img src="https://user-images.githubusercontent.com/5355/28694528-16e69d0c-72f8-11e7-91a7-c0b8cfc90391.gif" alt="direct-uploads"></p><p>To show the uploaded files in a form:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
// direct_uploads.js
addEventListener("direct-upload:initialize", event => {
const { target, detail } = event
const { id, file } = detail
target.insertAdjacentHTML("beforebegin", `
<div id="direct-upload-${id}" class="direct-upload direct-upload--pending">
<div id="direct-upload-progress-${id}" class="direct-upload__progress" style="width: 0%"></div>
<span class="direct-upload__filename">${file.name}</span>
</div>
`)
})
addEventListener("direct-upload:start", event => {
const { id } = event.detail
const element = document.getElementById(`direct-upload-${id}`)
element.classList.remove("direct-upload--pending")
})
addEventListener("direct-upload:progress", event => {
const { id, progress } = event.detail
const progressElement = document.getElementById(`direct-upload-progress-${id}`)
progressElement.style.width = `${progress}%`
})
addEventListener("direct-upload:error", event => {
event.preventDefault()
const { id, error } = event.detail
const element = document.getElementById(`direct-upload-${id}`)
element.classList.add("direct-upload--error")
element.setAttribute("title", error)
})
addEventListener("direct-upload:end", event => {
const { id } = event.detail
const element = document.getElementById(`direct-upload-${id}`)
element.classList.add("direct-upload--complete")
})
</pre>
</div>
<p>Add styles:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
/* direct_uploads.css */
.direct-upload {
display: inline-block;
position: relative;
padding: 2px 4px;
margin: 0 3px 3px 0;
border: 1px solid rgba(0, 0, 0, 0.3);
border-radius: 3px;
font-size: 11px;
line-height: 13px;
}
.direct-upload--pending {
opacity: 0.6;
}
.direct-upload__progress {
position: absolute;
top: 0;
left: 0;
bottom: 0;
opacity: 0.2;
background: #0076ff;
transition: width 120ms ease-out, opacity 60ms 60ms ease-in;
transform: translate3d(0, 0, 0);
}
.direct-upload--complete .direct-upload__progress {
opacity: 0.4;
}
.direct-upload--error {
border-color: red;
}
input[type=file][data-direct-upload-url][disabled] {
display: none;
}
</pre>
</div>
<h4 id="integrating-with-libraries-or-frameworks"><a class="anchorlink" href="#integrating-with-libraries-or-frameworks">9.4 Integrating with Libraries or Frameworks</a></h4><p>If you want to use the Direct Upload feature from a JavaScript framework, or
you want to integrate custom drag and drop solutions, you can use the
<code>DirectUpload</code> class for this purpose. Upon receiving a file from your library
of choice, instantiate a DirectUpload and call its create method. Create takes
a callback to invoke when the upload completes.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
import { DirectUpload } from "@rails/activestorage"
const input = document.querySelector('input[type=file]')
// Bind to file drop - use the ondrop on a parent element or use a
// library like Dropzone
const onDrop = (event) => {
event.preventDefault()
const files = event.dataTransfer.files;
Array.from(files).forEach(file => uploadFile(file))
}
// Bind to normal file selection
input.addEventListener('change', (event) => {
Array.from(input.files).forEach(file => uploadFile(file))
// you might clear the selected files from the input
input.value = null
})
const uploadFile = (file) => {
// your form needs the file_field direct_upload: true, which
// provides data-direct-upload-url
const url = input.dataset.directUploadUrl
const upload = new DirectUpload(file, url)
upload.create((error, blob) => {
if (error) {
// Handle the error
} else {
// Add an appropriately-named hidden input to the form with a
// value of blob.signed_id so that the blob ids will be
// transmitted in the normal upload flow
const hiddenField = document.createElement('input')
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("value", blob.signed_id);
hiddenField.name = input.name
document.querySelector('form').appendChild(hiddenField)
}
})
}
</pre>
</div>
<p>If you need to track the progress of the file upload, you can pass a third
parameter to the <code>DirectUpload</code> constructor. During the upload, DirectUpload
will call the object's <code>directUploadWillStoreFileWithXHR</code> method. You can then
bind your own progress handler on the XHR.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
import { DirectUpload } from "@rails/activestorage"
class Uploader {
constructor(file, url) {
this.upload = new DirectUpload(this.file, this.url, this)
}
upload(file) {
this.upload.create((error, blob) => {
if (error) {
// Handle the error
} else {
// Add an appropriately-named hidden input to the form
// with a value of blob.signed_id
}
})
}
directUploadWillStoreFileWithXHR(request) {
request.upload.addEventListener("progress",
event => this.directUploadDidProgress(event))
}
directUploadDidProgress(event) {
// Use event.loaded and event.total to update the progress bar
}
}
</pre>
</div>
<h3 id="discarding-files-stored-during-system-tests"><a class="anchorlink" href="#discarding-files-stored-during-system-tests">10 Discarding Files Stored During System Tests</a></h3><p>System tests clean up test data by rolling back a transaction. Because destroy
is never called on an object, the attached files are never cleaned up. If you
want to clear the files, you can do it in an <code>after_teardown</code> callback. Doing it
here ensures that all connections created during the test are complete and
you won't receive an error from Active Storage saying it can't find a file.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :chrome, screen_size: [1400, 1400]
def remove_uploaded_files
FileUtils.rm_rf("#{Rails.root}/storage_test")
end
def after_teardown
super
remove_uploaded_files
end
end
</pre>
</div>
<p>If your system tests verify the deletion of a model with attachments and you're
using Active Job, set your test environment to use the inline queue adapter so
the purge job is executed immediately rather at an unknown time in the future.</p><p>You may also want to use a separate service definition for the test environment
so your tests don't delete the files you create during development.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Use inline job processing to make things happen immediately
config.active_job.queue_adapter = :inline
# Separate file storage in the test environment
config.active_storage.service = :local_test
</pre>
</div>
<h3 id="discarding-files-stored-during-integration-tests"><a class="anchorlink" href="#discarding-files-stored-during-integration-tests">11 Discarding Files Stored During Integration Tests</a></h3><p>Similarly to System Tests, files uploaded during Integration Tests will not be
automatically cleaned up. If you want to clear the files, you can do it in an
<code>after_teardown</code> callback. Doing it here ensures that all connections created
during the test are complete and you won't receive an error from Active Storage
saying it can't find a file.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module RemoveUploadedFiles
def after_teardown
super
remove_uploaded_files
end
private
def remove_uploaded_files
FileUtils.rm_rf(Rails.root.join('tmp', 'storage'))
end
end
module ActionDispatch
class IntegrationTest
prepend RemoveUploadedFiles
end
end
</pre>
</div>
<h3 id="implementing-support-for-other-cloud-services"><a class="anchorlink" href="#implementing-support-for-other-cloud-services">12 Implementing Support for Other Cloud Services</a></h3><p>If you need to support a cloud service other than these, you will need to
implement the Service. Each service extends
<a href="https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/service.rb"><code>ActiveStorage::Service</code></a>
by implementing the methods necessary to upload and download files to the cloud.</p>
<h3>피드백</h3>
<p>
이 가이드의 품질을 향상시키기 위해 여러분의 도움이 필요하다.
</p>
<p>