-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing.html
1810 lines (1770 loc) · 157 KB
/
routing.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 prefix="og: http://ogp.me/ns#">
<head>
<meta charset="utf-8">
<meta content="Ruby on Rails, Ruby, Rails, Rails 3, Rails 4, Rails 5, Rails 6, Rails 6.0, Rails 6.1, Rails 7.0, Rails 7.1 руководство, начинающим, самоучитель, manual, мануал, справочник, учебник, примеры, Руби, рельсы" name="keywords"/>
<meta content="Ruby on Rails руководства, учебники, статьи на русском языке" name="description"/>
<meta content="website" property="og:type"/>
<meta content="Rusrails: Роутинг в Rails" property="og:title"/>
<meta content="Ruby on Rails руководства, учебники, статьи на русском языке" property="og:description"/>
<meta content="http://localhost:3000/routing" property="og:url"/>
<meta content="http://rusrails.ru/assets/rusrails.png" property="og:image"/>
<title>
Rusrails: Роутинг в Rails
</title>
<link rel="stylesheet" href="/assets/application-f9dfa6ce7fa871006d478e422639671663284ddaa3126cf81ddfe371ac3533c4.css" />
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="brand" href="/"></a>
<ul class="nav pull-right top-menu">
<li>
<a href="/">Главная</a>
</li>
<li class="dropdown">
<a class="index-popover" href="#">
Содержание
<b class="caret"></b>
</a> <div class="index-popover-content hide">
<ul><li><p><strong>С чего начать?</strong></p><ul><li><a href="/getting-started">Rails для начинающих</a>
</li></ul></li><li><p><strong>Модели</strong></p><ul><li><a href="/active-record-basics">Основы Active Record</a>
</li><li><a href="/active-record-migrations">Миграции Active Record</a>
</li><li><a href="/active-record-validations">Валидации Active Record</a>
</li><li><a href="/active-record-callbacks">Колбэки Active Record</a>
</li><li><a href="/active-record-associations">Связи (ассоциации) Active Record</a>
</li><li><a href="/active-record-querying">Интерфейс запросов Active Record</a>
</li><li><a href="/active-model-basics">Основы Active Model</a>
</li></ul></li><li><p><strong>Вью</strong></p><ul><li><a href="/action-view-overview">Обзор Action View</a>
</li><li><a href="/layouts-and-rendering">Макеты и рендеринг в Rails</a>
</li><li><a href="/action-view-helpers">Хелперы Action View</a>
</li><li><a href="/form-helpers">Хелперы форм в Action View</a>
</li></ul></li><li><p><strong>Контроллеры</strong></p><ul><li><a href="/action-controller-overview">Обзор Action Controller</a>
</li><li><a href="/routing">Роутинг в Rails</a>
</li></ul></li><li><p><strong>Другие компоненты</strong></p><ul><li><a href="/active-support-core-extensions">Расширения ядра Active Support</a>
</li><li><a href="/action-mailer-basics">Основы Action Mailer</a>
</li><li><a href="/action-mailbox-basics">Основы Action Mailbox</a>
</li><li><a href="/action-text-overview">Обзор Action Text</a>
</li><li><a href="/active_job_basics">Основы Active Job</a>
</li><li><a href="/active_storage_overview">Обзор Active Storage</a>
</li><li><a href="/action-cable-overview">Обзор Action Cable</a>
</li></ul></li><li><p><strong>Копаем глубже</strong></p><ul><li><a href="/i18n">API интернационализации Rails (I18n)</a>
</li><li><a href="/testing">Тестирование приложений на Rails</a>
</li><li><a href="/security">Безопасность приложений на Rails</a>
</li><li><a href="/error-reporting">Отчет об ошибках в приложениях Rails</a>
</li><li><a href="/debugging-rails-applications">Отладка приложений на Rails</a>
</li></ul></li></ul><p>next_column</p><ul><li><p><strong>Копаем глубже</strong></p><ul><li><a href="/configuring">Конфигурирование приложений на Rails</a>
</li><li><a href="/command-line">Командная строка Rails</a>
</li><li><a href="/asset-pipeline">Asset Pipeline</a>
</li><li><a href="/working-with-javascript-in-rails">Работа с JavaScript в Rails</a>
</li><li><a href="/initialization">Процесс инициализации в Rails</a>
</li><li><a href="/autoloading-and-reloading-constants">Автозагрузка и перезагрузка констант</a>
</li><li><a href="/caching-with-rails">Кэширование с Rails: Обзор</a>
</li><li><a href="/active-support-instrumentation">Инструментарий Active Support</a>
</li><li><a href="/api-app">Использование Rails для API-приложений</a>
</li><li><a href="/active-record-postgresql">Active Record для PostgreSQL</a>
</li><li><a href="/active-record-multiple-databases">Несколько баз данных с Active Record</a>
</li><li><a href="/active-record-encryption">Шифрование Active Record</a>
</li></ul></li><li><p><strong>Расширяем Rails</strong></p><ul><li><a href="/plugins">Основы создания плагинов Rails</a>
</li><li><a href="/rails-on-rack">Rails on Rack</a>
</li><li><a href="/generators">Создание и настройка генераторов и шаблонов Rails</a>
</li><li><a href="/engines">Engine для начинающих</a>
</li><li><a href="/threading_and_code_execution">Треды и выполнение кода в Rails</a>
</li><li><a href="/rails-application-templates">Шаблоны приложения Rails</a>
</li></ul></li><li><p><strong>Вносим вклад в Ruby on Rails</strong></p><ul><li><a href="/contributing_to_ruby_on_rails">Вносим вклад в Ruby on Rails</a>
</li><li><a href="/api_documentation_guidelines">Рекомендации по документированию API</a>
</li><li><a href="/ruby_on_rails_guides_guidelines">Рекомендации для руководств по Ruby on Rails</a>
</li><li><a href="/development_dependencies_install">Установка зависимостей для разработки</a>
</li><li><a href="/maintenance-policy">Политика поддержки (версий)</a>
</li></ul></li><li><p><strong>Заметки о релизах</strong></p><ul><li><a href="/upgrading-ruby-on-rails">Апгрейд Ruby on Rails</a>
</li><li><a href="/7_2_release_notes">Версия 7.2 - ?</a>
</li><li><a href="/7_1_release_notes">Версия 7.1 - Октябрь 2023</a>
</li><li><a href="/7_0_release_notes">Версия 7.0 - Декабрь 2021</a>
</li><li><a href="/6_1_release_notes">Версия 6.1 - Декабрь 2020</a>
</li><li><a href="/6_0_release_notes">Версия 6.0 - Август 2019</a>
</li></ul></li></ul>
</div>
</li>
<li>
<a href="/search">Поиск</a>
</li>
<li>
<a target="blank" href="http://api.rusrails.ru">Ruby & Rails API</a>
</li>
</ul>
</div>
</div>
</div>
<div class="content-wrapper">
<div class="container-fluid">
<div class="row-fluid">
<div class="span3 pull-right">
<div class="well social">
<h4>Принимаем пожелания и пул-реквесты!</h4>
<iframe allowtransparency="true" frameborder="0" height="30" src="http://ghbtns.com/github-btn.html?user=rusrails&repo=rusrails&type=watch&count=true&size=large" width="180"></iframe>
</div>
<div class="well menu">
<ul class="nav nav-list">
<li>
<h4>
<a href="#tsel-routera-rails">1. Цель роутера Rails</a>
</h4> </li>
<li>
<h5>
<a href="#soedinenie-url-s-kodom">1.1. Соединение URL с кодом</a>
</h5> </li>
<li>
<h5>
<a href="#sozdanie-url-iz-koda">1.2. Создание URL из кода</a>
</h5> </li>
<li>
<h5>
<a href="#nastroyka-marshrutizatora-rails">1.3. Настройка маршрутизатора Rails</a>
</h5> </li>
<li>
<h4>
<a href="#resource-routing-the-rails-default">2. Ресурсный роутинг: по умолчанию в Rails</a>
</h4> </li>
<li>
<h5>
<a href="#resursy-v-vebe">2.1. Ресурсы в вебе</a>
</h5> </li>
<li>
<h5>
<a href="#crud-metody-i-ekshny">2.2. CRUD, методы и экшны</a>
</h5> </li>
<li>
<h5>
<a href="#path-and-url-helpers">2.3. Путь и хелперы URL</a>
</h5> </li>
<li>
<h5>
<a href="#opredelenie-neskolkih-resursov-odnovremenno">2.4. Определение нескольких ресурсов одновременно</a>
</h5> </li>
<li>
<h5>
<a href="#singular-resources">2.5. Одиночные ресурсы</a>
</h5> </li>
<li>
<h5>
<a href="#prostranstvo-imen-kontrollera-i-routing">2.6. Пространство имен контроллера и роутинг</a>
</h5> </li>
<li>
<h5>
<a href="#vlozhennye-resursy">2.7. Вложенные ресурсы</a>
</h5> </li>
<li>
<h6>
<a href="#ogranicheniya-dlya-vlozheniya">2.7.1. Ограничения для вложения</a>
</h6> </li>
<li>
<h6>
<a href="#melkoe-vlozhenie">2.7.2. Мелкое вложение</a>
</h6> </li>
<li>
<h5>
<a href="#kontserny-marshrutov">2.8. Концерны маршрутов</a>
</h5> </li>
<li>
<h5>
<a href="#sozdanie-putey-i-url-iz-ob-ektov">2.9. Создание путей и URL из объектов</a>
</h5> </li>
<li>
<h5>
<a href="#opredelenie-dopolnitelnyh-ekshnov-restful">2.10. Определение дополнительных экшнов RESTful</a>
</h5> </li>
<li>
<h6>
<a href="#dobavlenie-marshrutov-k-elementam">2.10.1. Добавление маршрутов к элементам</a>
</h6> </li>
<li>
<h6>
<a href="#dobavlenie-marshrutov-k-kollektsii">2.10.2. Добавление маршрутов к коллекции</a>
</h6> </li>
<li>
<h6>
<a href="#dobavlenie-marshrutov-dlya-dopolnitelnyh-ekshnov-new">2.10.3. Добавление маршрутов для дополнительных экшнов new</a>
</h6> </li>
<li>
<h4>
<a href="#neresursnye-marshruty">3. Нересурсные маршруты</a>
</h4> </li>
<li>
<h5>
<a href="#neobyazatelnye-parametry">3.1. Необязательные параметры</a>
</h5> </li>
<li>
<h5>
<a href="#dynamic-segments">3.2. Динамические сегменты</a>
</h5> </li>
<li>
<h5>
<a href="#statichnye-segmenty">3.3. Статичные сегменты</a>
</h5> </li>
<li>
<h5>
<a href="#parametry-stroki-zaprosa">3.4. Параметры строки запроса</a>
</h5> </li>
<li>
<h5>
<a href="#opredelenie-znacheniy-po-umolchaniyu">3.5. Определение значений по умолчанию</a>
</h5> </li>
<li>
<h5>
<a href="#imenovanie-marshrutov">3.6. Именование маршрутов</a>
</h5> </li>
<li>
<h5>
<a href="#ogranicheniya-metoda-http">3.7. Ограничения метода HTTP</a>
</h5> </li>
<li>
<h5>
<a href="#segment-constraints">3.8. Ограничения сегмента</a>
</h5> </li>
<li>
<h5>
<a href="#ogranicheniya-osnovannye-na-zaprose">3.9. Ограничения, основанные на запросе</a>
</h5> </li>
<li>
<h5>
<a href="#advanced-constraints">3.10. Продвинутые ограничения</a>
</h5> </li>
<li>
<h6>
<a href="#ogranicheniya-v-blochnoy-forme">3.10.1. Ограничения в блочной форме</a>
</h6> </li>
<li>
<h5>
<a href="#podstanovka-marshrutov-i-podstanovochnye-segmenty">3.11. Подстановка маршрутов и подстановочные сегменты</a>
</h5> </li>
<li>
<h5>
<a href="#perenapravlenie">3.12. Перенаправление</a>
</h5> </li>
<li>
<h5>
<a href="#routing-k-prilozheniyam-rack">3.13. Роутинг к приложениям Rack</a>
</h5> </li>
<li>
<h5>
<a href="#ispolzovanie-root">3.14. Использование <code>root</code></a>
</h5> </li>
<li>
<h5>
<a href="#marshruty-s-simvolami-unicode">3.15. Маршруты с символами Unicode</a>
</h5> </li>
<li>
<h5>
<a href="#pryamye-marshruty">3.16. Прямые маршруты</a>
</h5> </li>
<li>
<h5>
<a href="#ispolzovanie-resolve">3.17. Использование <code>resolve</code></a>
</h5> </li>
<li>
<h4>
<a href="#nastroyka-resursnyh-marshrutov">4. Настройка ресурсных маршрутов</a>
</h4> </li>
<li>
<h5>
<a href="#opredelenie-ispolzuemogo-kontrollera">4.1. Определение используемого контроллера</a>
</h5> </li>
<li>
<h5>
<a href="#opredelenie-ogranicheniy">4.2. Определение ограничений</a>
</h5> </li>
<li>
<h5>
<a href="#pereopredelenie-imenovannyh-helperov-marshruta">4.3. Переопределение именованных хелперов маршрута</a>
</h5> </li>
<li>
<h5>
<a href="#pereopredelenie-segmentov-new-i-edit">4.4. Переопределение сегментов <code>new</code> и <code>edit</code></a>
</h5> </li>
<li>
<h5>
<a href="#prefiks-imenovannyh-marshrutnyh-helperov">4.5. Префикс именованных маршрутных хелперов</a>
</h5> </li>
<li>
<h6>
<a href="#parametrizovannye-prostranstva">4.5.1. Параметризованные пространства</a>
</h6> </li>
<li>
<h5>
<a href="#restricting-the-routes-created">4.6. Ограничение создаваемых маршрутов</a>
</h5> </li>
<li>
<h5>
<a href="#perevedennye-puti">4.7. Переведенные пути</a>
</h5> </li>
<li>
<h5>
<a href="#pereopredelenie-edinstvennogo-chisla">4.8. Переопределение единственного числа</a>
</h5> </li>
<li>
<h5>
<a href="#ispolzovanie-as-vo-vlozhennyh-resursah">4.9. Использование <code>:as</code> во вложенных ресурсах</a>
</h5> </li>
<li>
<h5>
<a href="#pereopredelenie-parametrov-imenovannyh-marshrutov">4.10. Переопределение параметров именованных маршрутов</a>
</h5> </li>
<li>
<h4>
<a href="#razdelenie-ochen-bolshogo-marshrutnogo-fayla-na-neskolko-nebolshih">5. Разделение <em>очень</em> большого маршрутного файла на несколько небольших</a>
</h4> </li>
<li>
<h5>
<a href="#ne-ispolzuyte-etu-osobennost-esli-vy-ne-nuzhdaetes-v-ney-realno">5.1. Не используйте эту особенность, если вы не нуждаетесь в ней реально</a>
</h5> </li>
<li>
<h4>
<a href="#osmotr-i-testirovanie-marshrutov">6. Осмотр и тестирование маршрутов</a>
</h4> </li>
<li>
<h5>
<a href="#listing-existing-routes">6.1. Список существующих маршрутов</a>
</h5> </li>
<li>
<h5>
<a href="#testirovanie-marshrutov">6.2. Тестирование маршрутов</a>
</h5> </li>
<li>
<h6>
<a href="#operator-kontrolya-assert_generates">6.2.1. Оператор контроля <code>assert_generates</code></a>
</h6> </li>
<li>
<h6>
<a href="#operator-kontrolya-assert_recognizes">6.2.2. Оператор контроля <code>assert_recognizes</code></a>
</h6> </li>
<li>
<h6>
<a href="#operator-kontrolya-assert_routing">6.2.3. Оператор контроля <code>assert_routing</code></a>
</h6> </li>
</ul>
</div>
<div class="well banner300 banner">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- sidebar rusrails -->
<ins class="adsbygoogle"
style="display:inline-block;width:300px;height:600px"
data-ad-client="ca-pub-7764391801669990"
data-ad-slot="6089520660"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
<div class="span9 content pull-left">
<div class="banner">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- top rusrails -->
<ins class="adsbygoogle"
style="display:inline-block;width:980px;height:120px"
data-ad-client="ca-pub-7764391801669990"
data-ad-slot="4891989065"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2 id='routing-v-rails' class='inside_page_header'> Роутинг в Rails</h2><p>Это руководство охватывает открытые для пользователя функции роутинга Rails.</p><p>После прочтения этого руководства вы узнаете:</p><ul><li>Как интерпретировать код в <code>config/routes.rb</code>
</li><li>Как создавать свои собственные маршруты, используя либо предпочтительный ресурсный стиль, либо метод <code>match</code>
</li><li>Как определять параметры маршрута, которые передаются в экшн контроллера
</li><li>Как автоматически создавать пути и URL, используя маршрутные хелперы
</li><li>О продвинутых техниках, таких как создание ограничений и монтирование точек назначения Rack
</li></ul><h3 id='tsel-routera-rails' class='inside_page_header'><a href="#tsel-routera-rails">1.</a> Цель роутера Rails</h3><p>Роутер Rails распознает URL и направляет его в экшн контроллера или в приложение Rack. Он также может генерировать пути и URL, избегая необходимость жестко прописывать строки в ваших вью.</p><h4 id='soedinenie-url-s-kodom' class='inside_page_header'><a href="#soedinenie-url-s-kodom">1.1.</a> Соединение URL с кодом</h4><p>Когда ваше приложение на Rails получает входящий запрос для:</p><div class="code_container">
<pre><code class="highlight plaintext">GET /patients/17
</code></pre>
</div>
<p>оно опрашивает роутер на предмет соответствия экшну контроллера. Если первый соответствующий маршрут это:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">get</span> <span class="s1">'/patients/:id'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'patients#show'</span>
</code></pre>
</div>
<p>то запрос будет направлен в контроллер <code>patients</code> в экшн <code>show</code> с <code>{ id: '17' }</code> в <code>params</code>.</p><div class="note"><p>Rails здесь использует именование в змеином_регистре (snake_case) для имен контроллера, если имя контроллера состоит из несколько слов, то, например, <code>MonsterTrucksController</code> необходимо использовать как <code>monster_trucks#show</code>.</p></div><h4 id='sozdanie-url-iz-koda' class='inside_page_header'><a href="#sozdanie-url-iz-koda">1.2.</a> Создание URL из кода</h4><p>Также можно генерировать пути и URL. Если вышеуказанный маршрут модифицировать на:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">get</span> <span class="s1">'/patients/:id'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'patients#show'</span><span class="p">,</span> <span class="ss">as: </span><span class="s1">'patient'</span>
</code></pre>
</div>
<p>и ваше приложение содержит код в контроллере:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="vi">@patient</span> <span class="o">=</span> <span class="no">Patient</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span>
</code></pre>
</div>
<p>и такой в соответствующей вью:</p><div class="code_container">
<pre><code class="highlight erb"><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s1">'Patient Record'</span><span class="p">,</span> <span class="n">patient_path</span><span class="p">(</span><span class="vi">@patient</span><span class="p">)</span> <span class="cp">%></span>
</code></pre>
</div>
<p>тогда роутер сгенерирует путь <code>/patients/17</code>. Это увеличит устойчивость вашей вью и упростит код для понимания. Отметьте, что id не нужно указывать в маршрутном хелпере.</p><h4 id='nastroyka-marshrutizatora-rails' class='inside_page_header'><a href="#nastroyka-marshrutizatora-rails">1.3.</a> Настройка маршрутизатора Rails</h4><p>Маршруты для приложения или engine располагаются в файле <code>config/routes.rb</code> и обычно выглядят так:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">routes</span><span class="p">.</span><span class="nf">draw</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:brands</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:index</span><span class="p">,</span> <span class="ss">:show</span><span class="p">]</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:products</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:index</span><span class="p">,</span> <span class="ss">:show</span><span class="p">]</span>
<span class="k">end</span>
<span class="n">resource</span> <span class="ss">:basket</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:show</span><span class="p">,</span> <span class="ss">:update</span><span class="p">,</span> <span class="ss">:destroy</span><span class="p">]</span>
<span class="n">resolve</span><span class="p">(</span><span class="s2">"Basket"</span><span class="p">)</span> <span class="p">{</span> <span class="n">route_for</span><span class="p">(</span><span class="ss">:basket</span><span class="p">)</span> <span class="p">}</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Поскольку это обычный исходный файл Ruby, можно использовать все его особенности, чтобы помочь определять маршруты, но необходимо быть осторожным с именами переменных, так как они могут конфликтовать с методами DSL маршрутизатора.</p><div class="note"><p>Блок <code>Rails.application.routes.draw do ... end</code>, который оборачивает определения маршрутов, требует создания области видимости для DSL маршрутизатора и не должен быть удален.</p></div><h3 id='resource-routing-the-rails-default' class='inside_page_header'><a href="#resource-routing-the-rails-default">2.</a> Ресурсный роутинг: по умолчанию в Rails</h3><p>Ресурсный роутинг позволяет быстро объявлять все общие маршруты для заданного ресурсного контроллера. Единственный вызов <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources"><code>resources</code></a> может объявить все маршруты, необходимые для экшнов <code>index</code>, <code>show</code>, <code>new</code>, <code>edit</code>, <code>create</code>, <code>update</code> и <code>destroy</code>.</p><h4 id='resursy-v-vebe' class='inside_page_header'><a href="#resursy-v-vebe">2.1.</a> Ресурсы в вебе</h4><p>Браузеры запрашивают страницы от Rails, выполняя запрос по URL, используя определенный метод HTTP, такой как <code>GET</code>, <code>POST</code>, <code>PATCH</code>, <code>PUT</code> и <code>DELETE</code>. Каждый метод - это запрос на выполнение операции с ресурсом. Ресурсный маршрут соединяет несколько родственных запросов с экшнами в одном контроллере.</p><p>Когда приложение на Rails получает входящий запрос для:</p><div class="code_container">
<pre><code class="highlight plaintext">DELETE /photos/17
</code></pre>
</div>
<p>оно просит роутер соединить его с экшном контроллера. Если первый соответствующий маршрут такой:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:photos</span>
</code></pre>
</div>
<p>Rails будет направлять этот запрос в экшн <code>destroy</code> контроллера <code>photos</code> с <code>{ id: '17' }</code> в <code>params</code>.</p><h4 id='crud-metody-i-ekshny' class='inside_page_header'><a href="#crud-metody-i-ekshny">2.2.</a> CRUD, методы и экшны</h4><p>В Rails ресурсный маршрут предоставляет сопоставление между методами HTTP и URL к экшнам контроллера. По соглашению, каждый экшн также соединяется с определенной операцией CRUD в базе данных. Одна запись в файле роутинга, такая как:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:photos</span>
</code></pre>
</div>
<p>создает семь различных маршрутов в приложении, все сопоставления с контроллером <code>Photos</code>:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Использование</th>
</tr>
<tr>
<td>GET</td>
<td>/photos</td>
<td>photos#index</td>
<td>отображает список всех фото</td>
</tr>
<tr>
<td>GET</td>
<td>/photos/new</td>
<td>photos#new</td>
<td>возвращает форму HTML для создания нового фото</td>
</tr>
<tr>
<td>POST</td>
<td>/photos</td>
<td>photos#create</td>
<td>создает новое фото</td>
</tr>
<tr>
<td>GET</td>
<td>/photos/:id</td>
<td>photos#show</td>
<td>отображает определенное фото</td>
</tr>
<tr>
<td>GET</td>
<td>/photos/:id/edit</td>
<td>photos#edit</td>
<td>возвращает форму HTML для редактирования фото</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/photos/:id</td>
<td>photos#update</td>
<td>обновляет определенное фото</td>
</tr>
<tr>
<td>DELETE</td>
<td>/photos/:id</td>
<td>photos#destroy</td>
<td>удаляет определенное фото</td>
</tr>
</table><div class="note"><p>Поскольку роутер использует как метод HTTP, так и URL, для сопоставления с входящими запросами, четыре URL соединяют с семью различными экшнами.</p></div><div class="note"><p>Маршруты Rails сравниваются в том порядке, в котором они определены, поэтому, если имеется <code>resources :photos</code> до <code>get 'photos/poll'</code> маршрут для экшна <code>show</code> в строчке <code>resources</code> совпадет до строчки <code>get</code>. Чтобы это исправить, переместите строчку <code>get</code> <strong>выше</strong> строчки <code>resources</code>, чтобы она сравнивалась первой.</p></div><h4 id='path-and-url-helpers' class='inside_page_header'><a href="#path-and-url-helpers">2.3.</a> Путь и хелперы URL</h4><p>Создание ресурсного маршрута также сделает доступными множество хелперов в контроллере вашего приложения. В случае с <code>resources :photos</code>:</p><ul><li><code>photos_path</code> возвращает <code>/photos</code>
</li><li><code>new_photo_path</code> возвращает <code>/photos/new</code>
</li><li><code>edit_photo_path(:id)</code> возвращает <code>/photos/:id/edit</code> (например, <code>edit_photo_path(10)</code> возвращает <code>/photos/10/edit</code>)
</li><li><code>photo_path(:id)</code> возвращает <code>/photos/:id</code> (например, <code>photo_path(10)</code> возвращает <code>/photos/10</code>)
</li></ul><p>Каждый из этих хелперов имеет соответствующий хелпер <code>_url</code> (такой как <code>photos_url</code>), который возвращает тот же путь с добавленными текущими хостом, портом и префиксом пути.</p><div class="info"><p>Чтобы найти имена маршрутных хелперов для ваших маршрутов, смотрите <a href="#listing-existing-routes">Список существующих маршрутов</a> ниже.</p></div><h4 id='opredelenie-neskolkih-resursov-odnovremenno' class='inside_page_header'><a href="#opredelenie-neskolkih-resursov-odnovremenno">2.4.</a> Определение нескольких ресурсов одновременно</h4><p>Если необходимо создать маршруты для более чем одного ресурса, можете сократить ввод, определив их в одном вызове <code>resources</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:photos</span><span class="p">,</span> <span class="ss">:books</span><span class="p">,</span> <span class="ss">:videos</span>
</code></pre>
</div>
<p>Это приведет к такому же результату, как и:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:photos</span>
<span class="n">resources</span> <span class="ss">:books</span>
<span class="n">resources</span> <span class="ss">:videos</span>
</code></pre>
</div>
<h4 id='singular-resources' class='inside_page_header'><a href="#singular-resources">2.5.</a> Одиночные ресурсы</h4><p>Иногда имеется ресурс, который клиенты всегда просматривают без ссылки на ID. Обычный пример, <code>/profile</code> всегда показывает профиль текущего зарегистрированного пользователя. Для этого можно использовать одиночный ресурс, чтобы связать <code>/profile</code> (а не <code>/profile/:id</code>) с экшном <code>show</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">get</span> <span class="s1">'profile'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'users#show'</span>
</code></pre>
</div>
<p>Передавая <code>String</code> в <code>to:</code> ожидается следующий формат - <code>controller#action</code>. Когда используется <code>Symbol</code>, опция <code>to:</code> должна быть заменена на <code>action:</code>. Когда используется <code>String</code> без <code>#</code>, опция <code>to:</code> должна быть заменена на <code>controller:</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">get</span> <span class="s1">'profile'</span><span class="p">,</span> <span class="ss">action: :show</span><span class="p">,</span> <span class="ss">controller: </span><span class="s1">'users'</span>
</code></pre>
</div>
<p>Этот ресурсный маршрут:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resource</span> <span class="ss">:geocoder</span>
<span class="n">resolve</span><span class="p">(</span><span class="s1">'Geocoder'</span><span class="p">)</span> <span class="p">{</span> <span class="p">[</span><span class="ss">:geocoder</span><span class="p">]</span> <span class="p">}</span>
</code></pre>
</div>
<p>создаст шесть различных маршрутов в приложении, все сопоставления с контроллером <code>Geocoders</code>:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Использование</th>
</tr>
<tr>
<td>GET</td>
<td>/geocoder/new</td>
<td>geocoders#new</td>
<td>возвращает форму HTML для создания нового геокодера</td>
</tr>
<tr>
<td>POST</td>
<td>/geocoder</td>
<td>geocoders#create</td>
<td>создает новый геокодер</td>
</tr>
<tr>
<td>GET</td>
<td>/geocoder</td>
<td>geocoders#show</td>
<td>отображает один и только один ресурс геокодера</td>
</tr>
<tr>
<td>GET</td>
<td>/geocoder/edit</td>
<td>geocoders#edit</td>
<td>возвращает форму HTML для редактирования геокодера</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/geocoder</td>
<td>geocoders#update</td>
<td>обновляет один и только один ресурс геокодера</td>
</tr>
<tr>
<td>DELETE</td>
<td>/geocoder</td>
<td>geocoders#destroy</td>
<td>удаляет ресурс геокодера</td>
</tr>
</table><div class="note"><p>Поскольку вы можете захотеть использовать один и тот же контроллер и для одиночного маршрута (<code>/account</code>), и для множественного маршрута (<code>/accounts/45</code>), одиночные ресурсы ведут на множественные контроллеры. По этой причине, например, <code>resource :photo</code> и <code>resources :photos</code> создадут и одиночные, и множественные маршруты, привязанные к одному и тому же контроллеру (<code>PhotosController</code>).</p></div><p>Одиночный ресурсный маршрут генерирует эти хелперы:</p><ul><li><code>new_geocoder_path</code> возвращает <code>/geocoder/new</code>
</li><li><code>edit_geocoder_path</code> возвращает <code>/geocoder/edit</code>
</li><li><code>geocoder_path</code> возвращает <code>/geocoder</code>
</li></ul><div class="note"><p>Вызов <code>resolve</code> необходим для преобразования экземпляров <code>Geocoder</code> в маршруты через <a href="/form-helpers#relying-on-record-identification">идентификацию записи</a>.</p></div><p>Как и в случае с множественными ресурсами, те же хелперы, оканчивающиеся на <code>_url</code> также включают хост, порт и префикс пути.</p><h4 id='prostranstvo-imen-kontrollera-i-routing' class='inside_page_header'><a href="#prostranstvo-imen-kontrollera-i-routing">2.6.</a> Пространство имен контроллера и роутинг</h4><p>Возможно, вы захотите организовать группы контроллеров в пространстве имен. Чаще всего группируют административные контроллеры в пространство имен <code>Admin::</code> и размещают их в директории <code>app/controllers/admin</code>. Можно маршрутизировать на такую группу с помощью блока <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-namespace"><code>namespace</code></a>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">namespace</span> <span class="ss">:admin</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:articles</span><span class="p">,</span> <span class="ss">:comments</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Это создаст ряд маршрутов для каждого контроллера <code>articles</code> и <code>comments</code>. Для <code>Admin::ArticlesController</code>, Rails создаст:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Именованный хелпер маршрута</th>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles</td>
<td>admin/articles#index</td>
<td>admin_articles_path</td>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles/new</td>
<td>admin/articles#new</td>
<td>new_admin_article_path</td>
</tr>
<tr>
<td>POST</td>
<td>/admin/articles</td>
<td>admin/articles#create</td>
<td>admin_articles_path</td>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles/:id</td>
<td>admin/articles#show</td>
<td>admin_article_path(:id)</td>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles/:id/edit</td>
<td>admin/articles#edit</td>
<td>edit_admin_article_path(:id)</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/admin/articles/:id</td>
<td>admin/articles#update</td>
<td>admin_article_path(:id)</td>
</tr>
<tr>
<td>DELETE</td>
<td>/admin/articles/:id</td>
<td>admin/articles#destroy</td>
<td>admin_article_path(:id)</td>
</tr>
</table><p>Если вместо этого хотите маршрут <code>/articles</code> (без префикса <code>/admin</code>) к <code>Admin::ArticlesController</code>, можно указать модуль в блоке <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-scope"><code>scope</code></a>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">scope</span> <span class="ss">module: </span><span class="s1">'admin'</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:articles</span><span class="p">,</span> <span class="ss">:comments</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Это также можно сделать одиночным маршрутом:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:articles</span><span class="p">,</span> <span class="ss">module: </span><span class="s1">'admin'</span>
</code></pre>
</div>
<p>Если вместо этого хотите маршрут <code>/admin/articles</code> к <code>ArticlesController</code> (без префикса модуля <code>Admin::</code>), можно указать путь с помощью блока <code>scope</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">scope</span> <span class="s1">'/admin'</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:articles</span><span class="p">,</span> <span class="ss">:comments</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Это также можно сделать одиночным маршрутом:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:articles</span><span class="p">,</span> <span class="ss">path: </span><span class="s1">'/admin/articles'</span>
</code></pre>
</div>
<p>В обоих случаях, хелперы именованных маршрутов остаются теми же, что и без использования <code>scope</code>. В последнем случае, следующие пути соединят с <code>ArticlesController</code>:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Именованный хелпер маршрута</th>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles</td>
<td>articles#index</td>
<td>articles_path</td>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles/new</td>
<td>articles#new</td>
<td>new_article_path</td>
</tr>
<tr>
<td>POST</td>
<td>/admin/articles</td>
<td>articles#create</td>
<td>articles_path</td>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles/:id</td>
<td>articles#show</td>
<td>article_path(:id)</td>
</tr>
<tr>
<td>GET</td>
<td>/admin/articles/:id/edit</td>
<td>articles#edit</td>
<td>edit_article_path(:id)</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/admin/articles/:id</td>
<td>articles#update</td>
<td>article_path(:id)</td>
</tr>
<tr>
<td>DELETE</td>
<td>/admin/articles/:id</td>
<td>articles#destroy</td>
<td>article_path(:id)</td>
</tr>
</table><div class="info"><p>Если хотите использовать другое пространство имен контроллера в блоке <code>namespace</code>, можно указать абсолютный путь контроллера, т.е: <code>get '/foo', to: '/foo#index'</code>.</p></div><h4 id='vlozhennye-resursy' class='inside_page_header'><a href="#vlozhennye-resursy">2.7.</a> Вложенные ресурсы</h4><p>Нормально иметь ресурсы, которые логически подчинены другим ресурсам. Например, предположим ваше приложение включает эти модели:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Magazine</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="n">has_many</span> <span class="ss">:ads</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">Ad</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="n">belongs_to</span> <span class="ss">:magazine</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Вложенные маршруты позволяют захватить эти отношения в вашем роутинге. В этом случае можете включить такое объявление маршрута:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:magazines</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:ads</span>
<span class="k">end</span>
</code></pre>
</div>
<p>В дополнение к маршрутам для magazines, это объявление также создаст маршруты для ads в <code>AdsController</code>. URL с ad требует magazine:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Использование</th>
</tr>
<tr>
<td>GET</td>
<td>/magazines/:magazine_id/ads</td>
<td>ads#index</td>
<td>отображает список всех ads для определенного magazine</td>
</tr>
<tr>
<td>GET</td>
<td>/magazines/:magazine_id/ads/new</td>
<td>ads#new</td>
<td>возвращает форму HTML для создания новой ad, принадлежащей определенному magazine</td>
</tr>
<tr>
<td>POST</td>
<td>/magazines/:magazine_id/ads</td>
<td>ads#create</td>
<td>создает новую ad, принадлежащую указанному magazine</td>
</tr>
<tr>
<td>GET</td>
<td>/magazines/:magazine_id/ads/:id</td>
<td>ads#show</td>
<td>отражает определенную ad, принадлежащую определенному magazine</td>
</tr>
<tr>
<td>GET</td>
<td>/magazines/:magazine_id/ads/:id/edit</td>
<td>ads#edit</td>
<td>возвращает форму HTML для редактирования ad, принадлежащей определенному magazine</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/magazines/:magazine_id/ads/:id</td>
<td>ads#update</td>
<td>обновляет определенную ad, принадлежащую определенному magazine</td>
</tr>
<tr>
<td>DELETE</td>
<td>/magazines/:magazine_id/ads/:id</td>
<td>ads#destroy</td>
<td>удаляет определенную ad, принадлежащую определенному magazine</td>
</tr>
</table><p>Также будут созданы маршрутные хелперы, такие как <code>magazine_ads_url</code> и <code>edit_magazine_ad_path</code>. Эти хелперы принимают экземпляр Magazine как первый параметр (<code>magazine_ads_url(@magazine)</code>).</p><h5 id='ogranicheniya-dlya-vlozheniya' class='inside_page_header'><a href="#ogranicheniya-dlya-vlozheniya">2.7.1.</a> Ограничения для вложения</h5><p>Вы можете вкладывать ресурсы в другие вложенные ресурсы, если хотите. Например:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:publishers</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:magazines</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:photos</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Глубоко вложенные ресурсы быстро становятся громоздкими. В этом случае, например, приложение будет распознавать пути, такие как:</p><div class="code_container">
<pre><code class="highlight plaintext">/publishers/1/magazines/2/photos/3
</code></pre>
</div>
<p>Соответствующий маршрутный хелпер будет <code>publisher_magazine_photo_url</code>, требующий определения объектов на всех трех уровнях. Действительно, эта ситуация достаточно запутана, так что в <a href="http://weblog.jamisbuck.org/2007/2/5/nesting-resources">статье Jamis Buck</a> предлагает правило хорошей разработки на Rails:</p><div class="info"><p>Ресурсы никогда не должны быть вложены глубже, чем на 1 уровень.</p></div><h5 id='melkoe-vlozhenie' class='inside_page_header'><a href="#melkoe-vlozhenie">2.7.2.</a> Мелкое вложение</h5><p>Один из способов избежать глубокой вложенности (как рекомендовано выше) состоит в том, чтобы генерировать экшны коллекции в области видимости родителя, получая представление об иерархии, но не вкладывать экшны элементов. Другими словами, создавать маршруты с минимальным количеством информации для однозначной идентификации ресурса, например так:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:articles</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:comments</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:index</span><span class="p">,</span> <span class="ss">:new</span><span class="p">,</span> <span class="ss">:create</span><span class="p">]</span>
<span class="k">end</span>
<span class="n">resources</span> <span class="ss">:comments</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:show</span><span class="p">,</span> <span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">,</span> <span class="ss">:destroy</span><span class="p">]</span>
</code></pre>
</div>
<p>Эта идея балансирует на грани между наглядностью маршрутов и глубоким вложением. Существует сокращенный синтаксис для получения подобного с помощью опции <code>:shallow</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:articles</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:comments</span><span class="p">,</span> <span class="ss">shallow: </span><span class="kp">true</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Это сгенерирует те же самые маршруты из первого примера. Также можно определить опцию <code>:shallow</code> в родительском ресурсе, в этом случае все вложенные ресурсы будут мелкие:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:articles</span><span class="p">,</span> <span class="ss">shallow: </span><span class="kp">true</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:comments</span>
<span class="n">resources</span> <span class="ss">:quotes</span>
<span class="n">resources</span> <span class="ss">:drafts</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Тут для ресурса articles будут сгенерированы следующие маршруты:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Именованный маршрутный хелпер</th>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/comments(.:format)</td>
<td>comments#index</td>
<td>article_comments_path</td>
</tr>
<tr>
<td>POST</td>
<td>/articles/:article_id/comments(.:format)</td>
<td>comments#create</td>
<td>article_comments_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/comments/new(.:format)</td>
<td>comments#new</td>
<td>new_article_comment_path</td>
</tr>
<tr>
<td>GET</td>
<td>/comments/:id/edit(.:format)</td>
<td>comments#edit</td>
<td>edit_comment_path</td>
</tr>
<tr>
<td>GET</td>
<td>/comments/:id(.:format)</td>
<td>comments#show</td>
<td>comment_path</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/comments/:id(.:format)</td>
<td>comments#update</td>
<td>comment_path</td>
</tr>
<tr>
<td>DELETE</td>
<td>/comments/:id(.:format)</td>
<td>comments#destroy</td>
<td>comment_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/quotes(.:format)</td>
<td>quotes#index</td>
<td>article_quotes_path</td>
</tr>
<tr>
<td>POST</td>
<td>/articles/:article_id/quotes(.:format)</td>
<td>quotes#create</td>
<td>article_quotes_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/quotes/new(.:format)</td>
<td>quotes#new</td>
<td>new_article_quote_path</td>
</tr>
<tr>
<td>GET</td>
<td>/quotes/:id/edit(.:format)</td>
<td>quotes#edit</td>
<td>edit_quote_path</td>
</tr>
<tr>
<td>GET</td>
<td>/quotes/:id(.:format)</td>
<td>quotes#show</td>
<td>quote_path</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/quotes/:id(.:format)</td>
<td>quotes#update</td>
<td>quote_path</td>
</tr>
<tr>
<td>DELETE</td>
<td>/quotes/:id(.:format)</td>
<td>quotes#destroy</td>
<td>quote_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/drafts(.:format)</td>
<td>drafts#index</td>
<td>article_drafts_path</td>
</tr>
<tr>
<td>POST</td>
<td>/articles/:article_id/drafts(.:format)</td>
<td>drafts#create</td>
<td>article_drafts_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/drafts/new(.:format)</td>
<td>drafts#new</td>
<td>new_article_draft_path</td>
</tr>
<tr>
<td>GET</td>
<td>/drafts/:id/edit(.:format)</td>
<td>drafts#edit</td>
<td>edit_draft_path</td>
</tr>
<tr>
<td>GET</td>
<td>/drafts/:id(.:format)</td>
<td>drafts#show</td>
<td>draft_path</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/drafts/:id(.:format)</td>
<td>drafts#update</td>
<td>draft_path</td>
</tr>
<tr>
<td>DELETE</td>
<td>/drafts/:id(.:format)</td>
<td>drafts#destroy</td>
<td>draft_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles(.:format)</td>
<td>articles#index</td>
<td>articles_path</td>
</tr>
<tr>
<td>POST</td>
<td>/articles(.:format)</td>
<td>articles#create</td>
<td>articles_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/new(.:format)</td>
<td>articles#new</td>
<td>new_article_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:id/edit(.:format)</td>
<td>articles#edit</td>
<td>edit_article_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:id(.:format)</td>
<td>articles#show</td>
<td>article_path</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/articles/:id(.:format)</td>
<td>articles#update</td>
<td>article_path</td>
</tr>
<tr>
<td>DELETE</td>
<td>/articles/:id(.:format)</td>
<td>articles#destroy</td>
<td>article_path</td>
</tr>
</table><p>Метод <a href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-shallow"><code>shallow</code></a> в DSL создает область видимости, в котором каждое вложение мелкое. Это генерирует те же самые маршруты из предыдущего примера:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">shallow</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:articles</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:comments</span>
<span class="n">resources</span> <span class="ss">:quotes</span>
<span class="n">resources</span> <span class="ss">:drafts</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Также существуют две опции для <code>scope</code> для настройки мелких маршрутов. <code>:shallow_path</code> добавляет к путям элемента префикс с указанным параметром:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">scope</span> <span class="ss">shallow_path: </span><span class="s2">"sekret"</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:articles</span> <span class="k">do</span>
<span class="n">resources</span> <span class="ss">:comments</span><span class="p">,</span> <span class="ss">shallow: </span><span class="kp">true</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
</div>
<p>Для ресурса комментариев будут сгенерированы следующие маршруты:</p><table class='table table-striped'><tr>
<th>Метод HTTP</th>
<th>Путь</th>
<th>Контроллер#Экшн</th>
<th>Именованный хелпер маршрута</th>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/comments(.:format)</td>
<td>comments#index</td>
<td>article_comments_path</td>
</tr>
<tr>
<td>POST</td>
<td>/articles/:article_id/comments(.:format)</td>
<td>comments#create</td>
<td>article_comments_path</td>
</tr>
<tr>
<td>GET</td>
<td>/articles/:article_id/comments/new(.:format)</td>
<td>comments#new</td>
<td>new_article_comment_path</td>
</tr>
<tr>
<td>GET</td>
<td>/sekret/comments/:id/edit(.:format)</td>
<td>comments#edit</td>
<td>edit_comment_path</td>
</tr>
<tr>
<td>GET</td>
<td>/sekret/comments/:id(.:format)</td>
<td>comments#show</td>
<td>comment_path</td>
</tr>
<tr>
<td>PATCH/PUT</td>
<td>/sekret/comments/:id(.:format)</td>
<td>comments#update</td>
<td>comment_path</td>