-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathchapter10.html
2047 lines (1752 loc) · 191 KB
/
chapter10.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="zh-CN">
<head>
<meta charset="utf-8"/>
<title>Ruby on Rails 教程 - 第 10 章 更新、显示和删除用户</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="最好的 Ruby on Rails 入门教程"/>
<meta name="keywords" content="ruby, rails, tutorial"/>
<meta name="author" content="Michael Hartl"/>
<meta name="translator" content="安道"/>
<meta name="generator" content="persie 0.0.5.1"/>
<link rel="stylesheet" type="text/css" href="//railstutorial-china.org/assets/css/main.css"/>
<link rel="stylesheet" type="text/css" href="book.css"/>
<script type="text/javascript" src="//railstutorial-china.org/assets/js/global.js"></script>
</head>
<body class="book-page">
<nav class="navbar">
<div class="container">
<div class="clearfix">
<a class="navbar-brand hidden-sm-up" href="//railstutorial-china.org/" title="Ruby on Rails 教程">Ruby on Rails 教程</a>
<button class="navbar-toggler hidden-sm-up pull-xs-right" type="button" data-toggle="collapse" data-target="#main-nav">☰</button>
</div>
<a class="navbar-brand hidden-xs-down" href="//railstutorial-china.org/" title="Ruby on Rails 教程">Ruby on Rails 教程</a>
<div class="collapse navbar-toggleable-xs pull-sm-right" id="main-nav">
<ul class="nav navbar-nav">
<li class="nav-item"><a class="nav-link" href="//railstutorial-china.org/" title="首页">首页</a></li>
<li class="nav-item"><a class="nav-link" href="//railstutorial-china.org/blog/" title="博客">博客</a></li>
<li class="nav-item active"><a class="nav-link" href="//railstutorial-china.org/book/" title="阅读">阅读</a></li>
<li class="nav-item"><a class="nav-link" href="//railstutorial-china.org/#ebook" title="电子书">电子书</a></li>
</ul>
</div>
</div>
</nav>
<div class="content">
<div class="container">
<div class="row">
<div class="col-lg-offset-2 col-lg-8">
<div class="book-versions">
选择版本:
<a class="btn btn-primary" href="//railstutorial-china.org/book/" title="Ruby on Rails 教程(原书第 4 版,针对 Rails 5)">Rails 5</a>
<a class="btn btn-secondary" href="//railstutorial-china.org/rails42/" title="Ruby on Rails 教程(原书第 3 版,针对 Rails 4.2)">Rails 4.2</a>
<a class="btn btn-secondary" href="//railstutorial-china.org/rails4/" title="Ruby on Rails 教程(原书第 3 版,针对 Rails 4.0)">Rails 4.0</a>
<a class="btn btn-secondary" href="//railstutorial-china.org/rails3/" title="Ruby on Rails 教程(原书第 2 版,针对 Rails 3.2)">Rails 3.2</a>
</div>
<div class="alert alert-warning">
<p>在线版的内容可能落后于电子书,如果想及时获得更新,请<a href="//railstutorial-china.org/#ebook" title="购买电子书">购买电子书</a>。</p>
</div>
<article class="article">
<section data-type="chapter" id="updating-showing-and-deleting-users">
<h1><span class="title-label">第 10 章</span> 更新、显示和删除用户</h1>
<p>本章我们要完成 <code>Users</code> 资源的 REST 动作(<a class="xref-link" href="chapter7.html#table-restful-users">表 7.1</a>),添加 <code>edit</code>、<code>update</code>、<code>index</code> 和 <code>destroy</code> 四个动作。首先我们要实现更新用户个人资料的功能,并借此实现权限机制(基于<a class="xref-link" href="chapter8.html#basic-login">第 8 章</a>实现的身份验证系统)。然后创建一个页面,列出所有用户(也需要验证身份),期间会介绍如何使用示例数据和分页。最后,我们要实现删除用户的功能,从数据库中删除用户记录。我们不会为所有用户都提供这种强大的功能,而是创建管理员,授权他们来删除其他用户。</p>
<section data-type="sect1" id="updating-users">
<h1><span class="title-label">10.1</span> 更新用户</h1>
<p>编辑用户信息的方法和创建新用户差不多(参见<a class="xref-link" href="chapter7.html#sign-up">第 7 章</a>),创建新用户的页面在 <code>new</code> 动作中渲染,而编辑用户的页面在 <code>edit</code> 动作中渲染;创建用户的过程在 <code>create</code> 动作中处理 <code>POST</code> 请求,编辑用户要在 <code>update</code> 动作中处理 <code>PATCH</code> 请求(<a class="xref-link" href="chapter3.html#aside-get-etc">旁注 3.2</a>)。二者之间最大的区别是,任何人都可以注册,但只有当前用户才能更新自己的信息。我们可以使用<a class="xref-link" href="chapter8.html#basic-login">第 8 章</a>实现的身份验证机制,通过前置过滤器(before filter)实现访问限制。</p>
<p>开始实现之前,我们先切换到 <code>updating-users</code> 主题分支:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>git checkout <span class="nt">-b</span> updating-users
</code></pre></div>
</div>
<section data-type="sect2" id="edit-form">
<h2><span class="title-label">10.1.1</span> 编辑表单</h2>
<p>我们先来创建编辑表单,构思图如<a class="xref-link" href="#fig-edit-user-mockup">图 10.1</a> 所示。<sup>[<a id="fn-ref-1" href="#fn-1">1</a>]</sup>为了把这个构思图转换成可以使用的页面,我们既要编写 <code>Users</code> 控制器的 <code>edit</code> 动作,还要创建编辑用户的视图。我们先来编写 <code>edit</code> 动作。在 <code>edit</code> 动作中我们要从数据库中读取相应的用户。由<a class="xref-link" href="chapter7.html#table-restful-users">表 7.1</a> 得知,用户的编辑页面地址是 /users/1/edit(假设用户的 ID 是 1)。我们知道用户的 ID 可以通过 <code>params[:id]</code> 获取,因此可以使用<a class="xref-link" href="#listing-initial-edit-action">代码清单 10.1</a> 中的代码查找用户。</p>
<div id="listing-initial-edit-action" data-type="listing">
<h5><span class="title-label">代码清单 10.1</span>:<code>Users</code> 控制器的 <code>edit</code> 动作</h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="k">def</span> <span class="nf">show</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">new</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">create</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">save</span>
<span class="n">log_in</span> <span class="vi">@user</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Welcome to the Sample App!"</span>
<span class="n">redirect_to</span> <span class="vi">@user</span>
<span class="k">else</span>
<span class="n">render</span> <span class="s1">'new'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">edit</span>
<span class="hll"> <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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></span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span>
<span class="ss">:password_confirmation</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<div id="fig-edit-user-mockup" class="figure"><img src="images/chapter10/edit_user_mockup_bootstrap.png" alt="edit user mockup bootstrap" /><div class="figcaption"><span class="title-label">图 10.1</span>:用户编辑页面的构思图</div></div>
<p>用户编辑页面的视图(要手动创建这个文件)如<a class="xref-link" href="#listing-user-edit-view">代码清单 10.2</a> 所示。注意,这个视图和<a class="xref-link" href="chapter7.html#listing-signup-form">代码清单 7.15</a> 中新建用户的视图相似,有很多重复的代码,所以可以重构,把共用的代码放到局部视图中,这个任务留作<a class="xref-link" href="#exercises-edit-form">练习</a>。</p>
<div id="listing-user-edit-view" data-type="listing">
<h5><span class="title-label">代码清单 10.2</span>:用户编辑页面的视图</h5>
<div class="source-file">app/views/users/edit.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s2">"Edit user"</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Update your profile<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">form_for</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">render</span> <span class="s1">'shared/error_messages'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:name</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">text_field</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:email</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">email_field</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="s2">"Confirmation"</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span> <span class="s2">"Save changes"</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"btn btn-primary"</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"gravatar_edit"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">gravatar_for</span> <span class="vi">@user</span> <span class="cp">%></span>
<span class="nt"><a</span> <span class="na">href=</span><span class="s">"http://gravatar.com/emails"</span> <span class="na">target=</span><span class="s">"_blank"</span><span class="nt">></span>change<span class="nt"></a></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
<p>这里再次用到了 <a class="xref-link" href="chapter7.html#signup-error-messages">7.3.3 节</a>创建的 <code>error_messages</code> 局部视图。顺便说一下,修改 Gravatar 头像的链接用到了 <code>target="_blank"</code>,目的是在新窗口或新标签页中打开网页。链接到第三方网站时有时会这么做。(这样打开网页有个安全隐患,对这个问题的处理留作<a class="xref-link" href="#exercises-edit-form">练习</a>。)</p>
<p><a class="xref-link" href="#listing-initial-edit-action">代码清单 10.1</a> 中定义了 <code>@user</code> 实例变量,所以编辑页面可以正确渲染,如<a class="xref-link" href="#fig-edit-page">图 10.2</a> 所示。从“Name”和“Email”字段可以看出,Rails 会自动使用 <code>@user</code> 变量的属性值填写相应的字段。</p>
<div id="fig-edit-page" class="figure"><img src="images/chapter10/edit_page_3rd_edition.png" alt="edit page 3rd edition" /><div class="figcaption"><span class="title-label">图 10.2</span>:编辑页面的初始版本,名字和电子邮件地址自动填入了值</div></div>
<p>查看用户编辑页面的 HTML 源码,会看到预期的表单标签,如<a class="xref-link" href="#listing-edit-form-html">代码清单 10.3</a> 所示(某些细节可能不同)。</p>
<div id="listing-edit-form-html" data-type="listing">
<h5><span class="title-label">代码清单 10.3</span>:<a class="xref-link" href="#listing-user-edit-view">代码清单 10.2</a> 定义的编辑表单生成的 HTML</h5>
<div class="highlight language-html"><pre><code><span class="nt"><form</span> <span class="na">accept-charset=</span><span class="s">"UTF-8"</span> <span class="na">action=</span><span class="s">"/users/1"</span> <span class="na">class=</span><span class="s">"edit_user"</span>
<span class="na">id=</span><span class="s">"edit_user_1"</span> <span class="na">method=</span><span class="s">"post"</span><span class="nt">></span>
<span class="nt"><input</span> <span class="na">name=</span><span class="s">"_method"</span> <span class="na">type=</span><span class="s">"hidden"</span> <span class="na">value=</span><span class="s">"patch"</span> <span class="nt">/></span>
.
.
.
<span class="nt"></form></span>
</code></pre></div>
</div>
<p>留意一下这个隐藏字段:</p>
<div data-type="listing">
<div class="highlight language-html"><pre><code><span class="nt"><input</span> <span class="na">name=</span><span class="s">"_method"</span> <span class="na">type=</span><span class="s">"hidden"</span> <span class="na">value=</span><span class="s">"patch"</span> <span class="nt">/></span>
</code></pre></div>
</div>
<p>因为 Web 浏览器不支持发送 <code>PATCH</code> 请求(<a class="xref-link" href="chapter7.html#table-restful-users">表 7.1</a> 中的 REST 动作要用),所以 Rails 在 <code>POST</code> 请求中使用这个隐藏字段把它伪装成 <code>PATCH</code> 请求。<sup>[<a id="fn-ref-2" href="#fn-2">2</a>]</sup></p>
<p>还有一个细节需要注意一下:<a class="xref-link" href="#listing-user-edit-view">代码清单 10.2</a> 和<a class="xref-link" href="chapter7.html#listing-signup-form">代码清单 7.15</a> 都使用了相同的 <code>form_for(@user)</code> 来构建表单,那么 Rails 是怎么知道创建新用户要发送 <code>POST</code> 请求,而编辑用户时要发送 <code>PATCH</code> 请求的呢?这个问题的答案是,通过 Active Record 提供的 <code>new_record?</code> 布尔值方法检测用户是新创建的还是已经存在于数据库中:</p>
<div data-type="listing">
<div class="highlight language-irb"><pre><code><span class="go">$ rails console</span>
<span class="go">>> User.new.new_record?</span>
<span class="p">=></span> <span class="kp">true</span>
<span class="o">>></span> <span class="no">User</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">new_record?</span>
<span class="o">=></span> <span class="kp">false</span>
</code></pre></div>
</div>
<p>所以使用 <code>form_for(@user)</code> 构建表单时,如果 <code>@user.new_record?</code> 返回 <code>true</code>,Rails 发送 <code>POST</code> 请求,否则发送 <code>PATCH</code> 请求。</p>
<p>最后,我们要把导航栏中指向编辑用户页面的链接换成真实的地址。很简单,我们直接使用<a class="xref-link" href="chapter7.html#table-restful-users">表 7.1</a> 中列出的 <code>edit_user_path</code> 具名路由,并把参数设为<a class="xref-link" href="chapter9.html#listing-persistent-current-user">代码清单 9.9</a> 中定义的 <code>current_user</code> 辅助方法:</p>
<div data-type="listing">
<div class="highlight language-erb"><pre><code><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Settings"</span><span class="p">,</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="n">current_user</span><span class="p">)</span> <span class="cp">%></span>
</code></pre></div>
</div>
<p>完整的视图如<a class="xref-link" href="#listing-settings-link">代码清单 10.4</a> 所示。</p>
<div id="listing-settings-link" data-type="listing">
<h5><span class="title-label">代码清单 10.4</span>:在网站布局中添加“Settings”链接的地址</h5>
<div class="source-file">app/views/layouts/_header.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="nt"><header</span> <span class="na">class=</span><span class="s">"navbar navbar-fixed-top navbar-inverse"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"container"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"sample app"</span><span class="p">,</span> <span class="n">root_path</span><span class="p">,</span> <span class="ss">id: </span><span class="s2">"logo"</span> <span class="cp">%></span>
<span class="nt"><nav></span>
<span class="nt"><ul</span> <span class="na">class=</span><span class="s">"nav navbar-nav navbar-right"</span><span class="nt">></span>
<span class="nt"><li></span><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Home"</span><span class="p">,</span> <span class="n">root_path</span> <span class="cp">%></span><span class="nt"></li></span>
<span class="nt"><li></span><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Help"</span><span class="p">,</span> <span class="n">help_path</span> <span class="cp">%></span><span class="nt"></li></span>
<span class="cp"><%</span> <span class="k">if</span> <span class="n">logged_in?</span> <span class="cp">%></span>
<span class="nt"><li></span><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Users"</span><span class="p">,</span> <span class="s1">'#'</span> <span class="cp">%></span><span class="nt"></li></span>
<span class="nt"><li</span> <span class="na">class=</span><span class="s">"dropdown"</span><span class="nt">></span>
<span class="nt"><a</span> <span class="na">href=</span><span class="s">"#"</span> <span class="na">class=</span><span class="s">"dropdown-toggle"</span> <span class="na">data-toggle=</span><span class="s">"dropdown"</span><span class="nt">></span>
Account <span class="nt"><b</span> <span class="na">class=</span><span class="s">"caret"</span><span class="nt">></b></span>
<span class="nt"></a></span>
<span class="nt"><ul</span> <span class="na">class=</span><span class="s">"dropdown-menu"</span><span class="nt">></span>
<span class="nt"><li></span><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Profile"</span><span class="p">,</span> <span class="n">current_user</span> <span class="cp">%></span><span class="nt"></li></span>
<span class="hll"> <span class="nt"><li></span><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Settings"</span><span class="p">,</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="n">current_user</span><span class="p">)</span> <span class="cp">%></span><span class="nt"></li></span></span>
<span class="nt"><li</span> <span class="na">class=</span><span class="s">"divider"</span><span class="nt">></li></span>
<span class="nt"><li></span>
<span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Log out"</span><span class="p">,</span> <span class="n">logout_path</span><span class="p">,</span> <span class="ss">method: :delete</span> <span class="cp">%></span>
<span class="nt"></li></span>
<span class="nt"></ul></span>
<span class="nt"></li></span>
<span class="cp"><%</span> <span class="k">else</span> <span class="cp">%></span>
<span class="nt"><li></span><span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Log in"</span><span class="p">,</span> <span class="n">login_path</span> <span class="cp">%></span><span class="nt"></li></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="nt"></ul></span>
<span class="nt"></nav></span>
<span class="nt"></div></span>
<span class="nt"></header></span>
</code></pre></div>
</div>
<h5 id="exercises-edit-form" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>前面说过,使用 <code>target="_blank"</code> 打开 URL 有个小安全隐患:打开的窗口获得了 HTML 文档对应的 <code>window</code> 对象。这样在新窗口中可以插入恶意内容,发起<a href="https://zh.wikipedia.org/wiki/%E9%92%93%E9%B1%BC%E5%BC%8F%E6%94%BB%E5%87%BB" class="external-link">钓鱼攻击</a>。链接著名的网站(如 Gravatar)基本上不存在这种隐患,不过我们可以在链接标签中把 <code>rel</code>(“relationship”)属性设为 <code>"noopener"</code>,完全避免这个问题。在<a class="xref-link" href="#listing-user-edit-view">代码清单 10.2</a> 中的 Gravatar 头像编辑链接中添加这个属性。</p>
</li>
<li>
<p>重构 <code>new.html.erb</code> 和 <code>edit.html.erb</code> 视图,使用<a class="xref-link" href="#listing-new-edit-partial">代码清单 10.5</a> 中的局部视图去除表单中的重复代码。重构后的视图如<a class="xref-link" href="#listing-new-user-with-partial">代码清单 10.6</a> 和<a class="xref-link" href="#listing-edit-user-with-partial">代码清单 10.7</a> 所示。注意,我们使用 <code>provide</code> 方法(<a class="xref-link" href="chapter3.html#layouts-and-embedded-ruby">3.4.3 节</a>用过)把布局中的重复去除了。<sup>[<a id="fn-ref-3" href="#fn-3">3</a>]</sup>(如果你做了<a class="xref-link" href="chapter7.html#listing-post-signup-form">代码清单 7.27</a> 对应的练习,无法像题中所说的那样做,请自己设法解决。我建议你使用<a class="xref-link" href="#listing-new-edit-partial">代码清单 10.5</a> 中传递变量的方式,把<a class="xref-link" href="#listing-new-user-with-partial">代码清单 10.6</a> 和<a class="xref-link" href="#listing-edit-user-with-partial">代码清单 10.7</a> 所需的 URL 传给<a class="xref-link" href="#listing-new-edit-partial">代码清单 10.5</a> 中的表单。)</p>
</li>
</ol>
<div id="listing-new-edit-partial" data-type="listing">
<h5><span class="title-label">代码清单 10.5</span>:供注册用户和编辑用户表单使用的局部视图</h5>
<div class="source-file">app/views/users/_form.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%=</span> <span class="n">form_for</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">render</span> <span class="s1">'shared/error_messages'</span><span class="p">,</span> <span class="ss">object: </span><span class="vi">@user</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:name</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">text_field</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:email</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">email_field</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password_confirmation</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span> <span class="k">yield</span><span class="p">(</span><span class="ss">:button_text</span><span class="p">),</span> <span class="ss">class: </span><span class="s2">"btn btn-primary"</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
</code></pre></div>
</div>
<div id="listing-new-user-with-partial" data-type="listing">
<h5><span class="title-label">代码清单 10.6</span>:在注册视图中使用局部视图</h5>
<div class="source-file">app/views/users/new.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s1">'Sign up'</span><span class="p">)</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:button_text</span><span class="p">,</span> <span class="s1">'Create my account'</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Sign up<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">render</span> <span class="s1">'form'</span> <span class="cp">%></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
<div id="listing-edit-user-with-partial" data-type="listing">
<h5><span class="title-label">代码清单 10.7</span>:在编辑视图中使用局部视图</h5>
<div class="source-file">app/views/users/edit.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s1">'Edit user'</span><span class="p">)</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:button_text</span><span class="p">,</span> <span class="s1">'Save changes'</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Update your profile<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">render</span> <span class="s1">'form'</span> <span class="cp">%></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"gravatar_edit"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">gravatar_for</span> <span class="vi">@user</span> <span class="cp">%></span>
<span class="nt"><a</span> <span class="na">href=</span><span class="s">"http://gravatar.com/emails"</span> <span class="na">target=</span><span class="s">"_blank"</span><span class="nt">></span>Change<span class="nt"></a></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
</section>
<section data-type="sect2" id="unsuccessful-edits">
<h2><span class="title-label">10.1.2</span> 编辑失败</h2>
<p>本节我们要处理编辑失败的情况,过程与处理注册失败差不多(<a class="xref-link" href="chapter7.html#unsuccessful-signups">7.3 节</a>)。我们要先定义 <code>update</code> 动作,把提交的 <code>params</code> 散列传给 <code>update_attributes</code> 方法(<a class="xref-link" href="chapter6.html#updating-user-objects">6.1.5 节</a>),更新用户,如<a class="xref-link" href="#listing-user-update-action-unsuccessful">代码清单 10.8</a> 所示。如果提交的数据无效,更新操作会返回 <code>false</code>,由 <code>else</code> 分支处理,重新渲染编辑页面。我们之前用过类似的处理方式,代码结构和第一个版 <code>create</code> 动作类似(<a class="xref-link" href="chapter7.html#listing-first-create-action">代码清单 7.18</a>)。</p>
<div id="listing-user-update-action-unsuccessful" data-type="listing">
<h5><span class="title-label">代码清单 10.8</span>:<code>update</code> 动作的初始版本</h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="k">def</span> <span class="nf">show</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">new</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">create</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="hll"> <span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">save</span></span>
<span class="n">log_in</span> <span class="vi">@user</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Welcome to the Sample App!"</span>
<span class="n">redirect_to</span> <span class="vi">@user</span>
<span class="k">else</span>
<span class="hll"> <span class="n">render</span> <span class="s1">'new'</span></span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">edit</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">update</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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>
<span class="hll"> <span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span></span>
<span class="c1"># 处理更新成功的情况</span>
<span class="k">else</span>
<span class="hll"> <span class="n">render</span> <span class="s1">'edit'</span></span>
<span class="k">end</span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span>
<span class="ss">:password_confirmation</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>注意调用 <code>update_attributes</code> 方法时指定的 <code>user_params</code> 参数,这是健壮参数(strong parameter),可以避免批量赋值带来的安全隐患(参见 <a class="xref-link" href="chapter7.html#strong-parameters">7.3.2 节</a>)。</p>
<p>因为 <code>User</code> 模型中定义了验证规则,而且<a class="xref-link" href="#listing-user-edit-view">代码清单 10.2</a> 渲染了错误消息局部视图,所以提交无效信息后会显示一些有用的错误消息,如<a class="xref-link" href="#fig-buggy-edit-with-invalid-information">图 10.3</a> 所示。</p>
<div id="fig-buggy-edit-with-invalid-information" class="figure"><img src="images/chapter10/edit_with_invalid_information_3rd_edition.png" alt="edit with invalid information 3rd edition" /><div class="figcaption"><span class="title-label">图 10.3</span>:提交编辑表单后显示的错误消息</div></div>
<h5 id="exercises-unssuccessful-edits" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>提交一些无效的用户名、电子邮件地址和密码,确认编辑表单不会接受这些信息。</p>
</li>
</ol>
</section>
<section data-type="sect2" id="testing-unsuccessful-edits">
<h2><span class="title-label">10.1.3</span> 编辑失败的测试</h2>
<p><a class="xref-link" href="#unsuccessful-edits">10.1.2 节</a>结束时编辑表单已经可以使用,按照<a class="xref-link" href="chapter3.html#aside-when-to-test">旁注 3.3</a> 中的测试指导方针,现在我们要编写集成测试捕获回归。和之前一样,首先要生成一个集成测试文件:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails generate integration_test users_edit
invoke test_unit
create <span class="nb">test</span>/integration/users_edit_test.rb
</code></pre></div>
</div>
<p>然后为编辑失败编写一个简单的测试,如<a class="xref-link" href="#listing-unsuccessful-edit-test">代码清单 10.9</a> 所示。在这段测试中,我们检查提交无效信息后是否重新渲染编辑模板,以此确认行为是否正确。注意,这里使用 <code>patch</code> 方法发送 <code>PATCH</code> 请求,它的用法与 <code>get</code>、<code>post</code> 和 <code>delete</code> 类似。</p>
<div id="listing-unsuccessful-edit-test" data-type="listing">
<h5><span class="title-label">代码清单 10.9</span>:编辑失败的测试 <span class="green">GREEN</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UsersEditTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"unsuccessful edit"</span> <span class="k">do</span>
<span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
<span class="n">assert_template</span> <span class="s1">'users/edit'</span>
<span class="n">patch</span> <span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">),</span> <span class="ss">params: </span><span class="p">{</span> <span class="ss">user: </span><span class="p">{</span> <span class="ss">name: </span><span class="s2">""</span><span class="p">,</span>
<span class="ss">email: </span><span class="s2">"foo@invalid"</span><span class="p">,</span>
<span class="ss">password: </span><span class="s2">"foo"</span><span class="p">,</span>
<span class="ss">password_confirmation: </span><span class="s2">"bar"</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_template</span> <span class="s1">'users/edit'</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>此时,测试组件应该可以通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.10</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<h5 id="exercises-testing-unsuccessful-edits" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>在<a class="xref-link" href="#listing-unsuccessful-edit-test">代码清单 10.9</a> 中添加一行代码,确认错误消息的数量正确。提示:使用 <code>assert_select</code> 方法(<a class="xref-link" href="chapter5.html#table-assert-select">表 5.2</a>)确认 CSS 类为 <code>alert</code> 的 <code>div</code> 标签中有没有文本“The form contains 4 errors”。</p>
</li>
</ol>
</section>
<section data-type="sect2" id="successful-edits">
<h2><span class="title-label">10.1.4</span> 编辑成功(使用 TDD)</h2>
<p>现在我们要让编辑表单能正常使用。编辑头像的功能已经有了,因为我们把上传头像的操作交由 Gravatar 处理,如需更换头像,点击<a class="xref-link" href="#fig-edit-page">图 10.2</a> 中的“change”链接就可以了,如<a class="xref-link" href="#fig-gravatar-cropper">图 10.4</a> 所示。下面我们来实现编辑其他信息的功能。</p>
<div id="fig-gravatar-cropper" class="figure"><img src="images/chapter10/gravatar_cropper.png" alt="gravatar cropper" /><div class="figcaption"><span class="title-label">图 10.4</span>:Gravatar 的图像裁切界面,上传了一位<a href="http://www.michaelhartl.com/" class="external-link">帅哥</a>的图片</div></div>
<p>上手测试后,你可能会发现,编写应用代码之前编写测试比之后再写更有用。针对现在这种情况,我们要编写的是验收测试(acceptance test),由测试的结果决定某个功能是否完成。为了演示如何编写验收测试,我们将使用测试驱动开发技术完成用户编辑功能。</p>
<p>我们要编写与<a class="xref-link" href="#listing-unsuccessful-edit-test">代码清单 10.9</a> 类似的测试,确认更新用户的操作行为正确,只不过这一次我们会提交有效的信息。然后检查显示了闪现消息,而且成功重定向到了用户的资料页面,同时还要确认数据库中保存的用户信息也正确更新了。这个测试如<a class="xref-link" href="#listing-successful-edit-test">代码清单 10.11</a> 所示。注意,在<a class="xref-link" href="#listing-successful-edit-test">代码清单 10.11</a> 中,密码和密码确认都为空值,因为修改用户名和电子邮件地址时并不想修改密码。还要注意,我们使用 <code>@user.reload</code>(<a class="xref-link" href="chapter6.html#updating-user-objects">6.1.5 节</a>首次用到)重新加载数据库中存储的值,以此确认成功更新了信息。(新手很容易忘记这个操作,这就是为什么必须要有一定的经验才能编写有效的验收测试(以及 TDD)的原因。)</p>
<div id="listing-successful-edit-test" data-type="listing">
<h5><span class="title-label">代码清单 10.11</span>:编辑成功的测试 <span class="red">RED</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UsersEditTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">test</span> <span class="s2">"successful edit"</span> <span class="k">do</span>
<span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
<span class="n">assert_template</span> <span class="s1">'users/edit'</span>
<span class="nb">name</span> <span class="o">=</span> <span class="s2">"Foo Bar"</span>
<span class="n">email</span> <span class="o">=</span> <span class="s2">"[email protected]"</span>
<span class="n">patch</span> <span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">),</span> <span class="ss">params: </span><span class="p">{</span> <span class="ss">user: </span><span class="p">{</span> <span class="ss">name: </span><span class="nb">name</span><span class="p">,</span>
<span class="ss">email: </span><span class="n">email</span><span class="p">,</span>
<span class="ss">password: </span><span class="s2">""</span><span class="p">,</span>
<span class="ss">password_confirmation: </span><span class="s2">""</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="vi">@user</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">reload</span>
<span class="n">assert_equal</span> <span class="nb">name</span><span class="p">,</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">name</span>
<span class="n">assert_equal</span> <span class="n">email</span><span class="p">,</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">email</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>要让<a class="xref-link" href="#listing-successful-edit-test">代码清单 10.11</a> 中的测试通过,我们可以参照最终版 <code>create</code> 动作(<a class="xref-link" href="chapter8.html#listing-login-upon-signup">代码清单 8.25</a>)编写 <code>update</code> 动作,如<a class="xref-link" href="#listing-user-update-action">代码清单 10.12</a> 所示。</p>
<div id="listing-user-update-action" data-type="listing">
<h5><span class="title-label">代码清单 10.12</span>:<code>Users</code> 控制器的 <code>update</code> 动作 <span class="red">RED</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">def</span> <span class="n">update</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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>
<span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="hll"> <span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Profile updated"</span></span>
<span class="hll"> <span class="n">redirect_to</span> <span class="vi">@user</span></span>
<span class="k">else</span>
<span class="n">render</span> <span class="s1">'edit'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>如<a class="xref-link" href="#listing-user-update-action">代码清单 10.12</a> 的标题所示,测试组件无法通过,因为密码长度验证(<a class="xref-link" href="chapter6.html#listing-password-implementation">代码清单 6.42</a>)失败了,这是因为<a class="xref-link" href="#listing-successful-edit-test">代码清单 10.11</a> 中密码和密码确认都是空值。为了让测试通过,我们要在密码为空值时特殊处理最短长度验证,方法是把 <code>allow_nil: true</code> 选项传给 <code>validates</code> 方法,如<a class="xref-link" href="#listing-allow-blank-password">代码清单 10.13</a> 所示。</p>
<div id="listing-allow-blank-password" data-type="listing">
<h5><span class="title-label">代码清单 10.13</span>:更新时允许密码为空 <span class="green">GREEN</span></h5>
<div class="source-file">app/models/user.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="nb">attr_accessor</span> <span class="ss">:remember_token</span>
<span class="n">before_save</span> <span class="p">{</span> <span class="nb">self</span><span class="p">.</span><span class="nf">email</span> <span class="o">=</span> <span class="n">email</span><span class="p">.</span><span class="nf">downcase</span> <span class="p">}</span>
<span class="n">validates</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">length: </span><span class="p">{</span> <span class="ss">maximum: </span><span class="mi">50</span> <span class="p">}</span>
<span class="no">VALID_EMAIL_REGEX</span> <span class="o">=</span> <span class="sr">/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i</span>
<span class="n">validates</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">length: </span><span class="p">{</span> <span class="ss">maximum: </span><span class="mi">255</span> <span class="p">},</span>
<span class="ss">format: </span><span class="p">{</span> <span class="ss">with: </span><span class="no">VALID_EMAIL_REGEX</span> <span class="p">},</span>
<span class="ss">uniqueness: </span><span class="p">{</span> <span class="ss">case_sensitive: </span><span class="kp">false</span> <span class="p">}</span>
<span class="n">has_secure_password</span>
<span class="hll"> <span class="n">validates</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">length: </span><span class="p">{</span> <span class="ss">minimum: </span><span class="mi">6</span> <span class="p">},</span> <span class="ss">allow_nil: </span><span class="kp">true</span></span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>你可能担心这么改用户注册时可以把密码设为空值,其实不然,<a class="xref-link" href="chapter6.html#minimum-password-standards">6.3.3 节</a>说过,创建对象时,<code>has_secure_password</code> 会执行存在性验证,捕获密码为 <code>nil</code> 的情况。(密码为 <code>nil</code> 时能通过存在性验证,可是会被 <code>has_secure_password</code> 方法的验证捕获,因此修正了 <a class="xref-link" href="chapter7.html#signup-error-messages">7.3.3 节</a>提到的错误消息重复问题。)</p>
<p>至此,用户编辑页面应该可以正常使用了,如<a class="xref-link" href="#fig-edit-form-working">图 10.5</a> 所示。你也可以运行测试组件确认一下,应该可以通过。</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.14</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<div id="fig-edit-form-working" class="figure"><img src="images/chapter10/edit_form_working_new.png" alt="edit form working new" /><div class="figcaption"><span class="title-label">图 10.5</span>:编辑成功后显示的页面</div></div>
<h5 id="exercises-enabling-edits" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>在开发环境中确认可以编辑用户资料。</p>
</li>
<li>
<p>如果把电子邮件地址改成没有关联 Gravatar 头像的地址会怎样?</p>
</li>
</ol>
</section>
</section>
<section data-type="sect1" id="authorization">
<h1><span class="title-label">10.2</span> 权限系统</h1>
<p>在 Web 应用中,身份验证系统的功能是识别网站的用户,而权限系统是控制用户可以做什么操作。<a class="xref-link" href="chapter8.html#basic-login">第 8 章</a>实现的身份验证机制有一个很好的作用——可以实现权限系统。</p>
<p>虽然 <a class="xref-link" href="#updating-users">10.1 节</a>已经完成了 <code>edit</code> 和 <code>update</code> 动作,但是却有一个荒唐的安全隐患:任何人(甚至是未登录的用户)都可以访问这两个动作,更新任何用户的资料。本节我们要实现一种安全机制,限制用户必须先登录才能更新自己的资料,而且不能更新别人的资料。</p>
<p><a class="xref-link" href="#requiring-logged-in-users">10.2.1 节</a>将处理未登录用户试图访问有权访问的保护页面。因为在使用应用的过程中经常会发生这种情况,所以我们将把这些用户转向登录页面,而且会显示一个帮助消息,构思图如<a class="xref-link" href="#fig-login-page-protected-mockup">图 10.6</a> 所示。另一种情况是,用户尝试访问没有权限查看的页面(例如已登录的用户试图访问其他用户的编辑页面),此时将把用户重定向到根地址(<a class="xref-link" href="#requiring-the-right-user">10.2.2 节</a>)。</p>
<div id="fig-login-page-protected-mockup" class="figure"><img src="images/chapter10/login_page_protected_mockup.png" alt="login page protected mockup" /><div class="figcaption"><span class="title-label">图 10.6</span>:访问受保护页面时看到的页面构思图</div></div>
<section data-type="sect2" id="requiring-logged-in-users">
<h2><span class="title-label">10.2.1</span> 必须先登录</h2>
<p>为了实现<a class="xref-link" href="#fig-login-page-protected-mockup">图 10.6</a> 中的转向行为,我们要在 <code>Users</code> 控制器中使用前置过滤器。前置过滤器通过 <code>before_action</code> 方法设定,指定在某个动作运行前调用某个方法。<sup>[<a id="fn-ref-4" href="#fn-4">4</a>]</sup>为了实现要求用户先登录的限制,我们将定义一个名为 <code>logged_in_user</code> 的方法,然后使用 <code>before_action :logged_in_user</code> 调用这个方法,如<a class="xref-link" href="#listing-authorize-before-filter">代码清单 10.15</a> 所示。</p>
<div id="listing-authorize-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 10.15</span>:添加 <code>logged_in_user</code> 前置过滤器 <span class="red">RED</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="hll"> <span class="n">before_action</span> <span class="ss">:logged_in_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span></span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span>
<span class="ss">:password_confirmation</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># 前置过滤器</span>
<span class="c1"># 确保用户已登录</span>
<span class="k">def</span> <span class="nf">logged_in_user</span>
<span class="hll"> <span class="k">unless</span> <span class="n">logged_in?</span></span>
<span class="hll"> <span class="n">flash</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Please log in."</span></span>
<span class="hll"> <span class="n">redirect_to</span> <span class="n">login_url</span></span>
<span class="hll"> <span class="k">end</span></span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>默认情况下,前置过滤器会应用于控制器中的所有动作,所以在上述代码中我们传入了 <code>:only</code> 选项,指定只应用在 <code>edit</code> 和 <code>update</code> 两个动作上。</p>
<p>退出后再访问用户编辑页面 /users/1/edit,可以看到这个前置过滤器的效果,如<a class="xref-link" href="#fig-protected-log-in">图 10.7</a> 所示。</p>
<p>如<a class="xref-link" href="#listing-authorize-before-filter">代码清单 10.15</a> 的标题所示,现在测试组件无法通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.16</span>:<strong class="red">RED</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<p>这是因为现在 <code>edit</code> 和 <code>update</code> 动作都需要用户先登录,而在相应的测试中没有已登录的用户。</p>
<p>所以,在测试中访问 <code>edit</code> 和 <code>update</code> 动作之前,要先登入用户。这个操作可以通过 <a class="xref-link" href="chapter9.html#remember-tests">9.3 节</a>定义的 <code>log_in_as</code> 辅助方法(<a class="xref-link" href="chapter9.html#listing-test-helper-log-in">代码清单 9.24</a>)轻易实现,如<a class="xref-link" href="#listing-edit-tests-logged-in">代码清单 10.17</a> 所示。</p>
<div id="fig-protected-log-in" class="figure"><img src="images/chapter10/protected_log_in_3rd_edition.png" alt="protected log in 3rd edition" /><div class="figcaption"><span class="title-label">图 10.7</span>:尝试访问受保护页面后显示的登录表单</div></div>
<div id="listing-edit-tests-logged-in" data-type="listing">
<h5><span class="title-label">代码清单 10.17</span>:登入测试用户 <span class="green">GREEN</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UsersEditTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"unsuccessful edit"</span> <span class="k">do</span>
<span class="hll"> <span class="n">log_in_as</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span></span>
<span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
<span class="nb">test</span> <span class="s2">"successful edit"</span> <span class="k">do</span>
<span class="hll"> <span class="n">log_in_as</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span></span>
<span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>(可以把登入测试用户的代码放在 <code>setup</code> 方法中,去除一些重复。但是,在 <a class="xref-link" href="#friendly-forwarding">10.2.3 节</a>我们要修改其中一个测试,在登录前访问编辑页面,如果把登录操作放在 <code>setup</code> 方法中就不能先访问其他页面了。)</p>
<p>现在,测试组件应该可以通过了:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.18</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<p>测试组件虽然通过了,但是对前置过滤器的测试还没完,因为即便把安全防护去掉,测试也能通过。你可以把前置过滤器注释掉确认一下,如<a class="xref-link" href="#listing-commented-out-before-filter">代码清单 10.19</a> 所示。这可不妙!在测试组件能捕获的所有回归中,重大安全漏洞或许是最重要的。按照<a class="xref-link" href="#listing-commented-out-before-filter">代码清单 10.19</a> 的方式修改后,绝对不能让测试通过。下面我们编写测试捕获这个问题。</p>
<div id="listing-commented-out-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 10.19</span>:注释掉前置过滤器,测试安全防护措施 <span class="green">GREEN</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="c1"># before_action :logged_in_user, only: [:edit, :update]</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>前置过滤器应用在指定的各个动作上,因此我们要在 <code>Users</code> 控制器的测试中编写相应的测试。我们计划使用正确的请求方法访问 <code>edit</code> 和 <code>update</code> 动作,然后确认把用户重定向到了登录路径。由<a class="xref-link" href="chapter7.html#table-restful-users">表 7.1</a> 得知,正确的请求方法分别是 <code>GET</code> 和 <code>PATCH</code>,所以在测试中要使用 <code>get</code> 和 <code>patch</code> 方法,如<a class="xref-link" href="#listing-edit-update-redirect-tests">代码清单 10.20</a> 所示。</p>
<div id="listing-edit-update-redirect-tests" data-type="listing">
<h5><span class="title-label">代码清单 10.20</span>:测试 <code>edit</code> 和 <code>update</code> 动作是受保护的 <span class="red">RED</span></h5>
<div class="source-file">test/controllers/users_controller_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UsersControllerTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">test</span> <span class="s2">"should redirect edit when not logged in"</span> <span class="k">do</span>
<span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="n">login_url</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"should redirect update when not logged in"</span> <span class="k">do</span>
<span class="n">patch</span> <span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">),</span> <span class="ss">params: </span><span class="p">{</span> <span class="ss">user: </span><span class="p">{</span> <span class="ss">name: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">name</span><span class="p">,</span>
<span class="ss">email: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">email</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="n">login_url</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>注意,<a class="xref-link" href="#listing-edit-update-redirect-tests">代码清单 10.20</a> 中的第二个测试使用 <code>patch</code> 方法向 <code>user_path(@user)</code> 发送 <code>PATCH</code> 请求。根据<a class="xref-link" href="chapter7.html#table-restful-users">表 7.1</a>,这个请求由 <code>Users</code> 控制器的 <code>update</code> 动作处理。</p>
<p>测试组件现在无法通过,和我们预期的一样。为了让测试通过,我们只需把前置过滤器的注释去掉,如<a class="xref-link" href="#listing-uncommented-before-filter">代码清单 10.21</a> 所示。</p>
<div id="listing-uncommented-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 10.21</span>:去掉前置过滤器的注释 <span class="green">GREEN</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="hll"> <span class="n">before_action</span> <span class="ss">:logged_in_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span></span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>这样修改之后,测试组件应该可以通过了:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.22</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<p>如果不小心让未授权的用户能访问 <code>edit</code> 动作,现在测试组件能立即捕获。</p>
<h5 id="exercises-requiring-logged-in-users" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>前面说过,前置过滤器默认应用到控制器中的全部动作上。如果这样,会导致我们的应用出错(例如登录后才能访问注册页面,这显然是不对的)。把<a class="xref-link" href="#listing-authorize-before-filter">代码清单 10.15</a> 中的 <code>only:</code> 散列注释掉,确认测试组件能捕获这个问题。</p>
</li>
</ol>
</section>
<section data-type="sect2" id="requiring-the-right-user">
<h2><span class="title-label">10.2.2</span> 用户只能编辑自己的资料</h2>
<p>当然,要求用户必须先登录还不够,用户必须只能编辑自己的资料。由 <a class="xref-link" href="#requiring-logged-in-users">10.2.1 节</a>得知,测试组件很容易漏掉基本的安全缺陷,所以我们将使用测试驱动开发技术确保写出的代码能正确实现安全机制。为此,我们要在 <code>Users</code> 控制器的测试中添加一些测试,完善<a class="xref-link" href="#listing-edit-update-redirect-tests">代码清单 10.20</a>。</p>
<p>为了确保用户不能编辑其他用户的信息,我们需要登入第二个用户。为此,要在用户固件文件中再添加一个用户,如<a class="xref-link" href="#listing-fixture-second-user">代码清单 10.23</a> 所示。</p>
<div id="listing-fixture-second-user" data-type="listing">
<h5><span class="title-label">代码清单 10.23</span>:在固件文件中添加第二个用户</h5>
<div class="source-file">test/fixtures/users.yml</div>
<div class="highlight language-yaml"><pre><code><span class="na">michael</span><span class="pi">:</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">Michael Example</span>
<span class="na">email</span><span class="pi">:</span> <span class="s">[email protected]</span>
<span class="na">password_digest</span><span class="pi">:</span> <span class="s"><%= User.digest('password') %></span>
<span class="hll"><span class="na">archer</span><span class="pi">:</span></span>
<span class="hll"> <span class="na">name</span><span class="pi">:</span> <span class="s">Sterling Archer</span></span>
<span class="hll"> <span class="na">email</span><span class="pi">:</span> <span class="s">[email protected]</span></span>
<span class="hll"> <span class="na">password_digest</span><span class="pi">:</span> <span class="s"><%= User.digest('password') %></span></span>
</code></pre></div>
</div>
<p>使用<a class="xref-link" href="chapter9.html#listing-test-helper-log-in">代码清单 9.24</a> 中定义的 <code>log_in_as</code> 方法,我们可以使用<a class="xref-link" href="#listing-edit-update-wrong-user-tests">代码清单 10.24</a> 中的代码测试 <code>edit</code> 和 <code>update</code> 动作。注意,这里没有重定向到登录路径,而是根地址,因为试图编辑其他用户资料的用户已经登录了。</p>
<div id="listing-edit-update-wrong-user-tests" data-type="listing">
<h5><span class="title-label">代码清单 10.24</span>:尝试编辑其他用户资料的测试 <span class="red">RED</span></h5>
<div class="source-file">test/controllers/users_controller_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UsersControllerTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="hll"> <span class="vi">@other_user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:archer</span><span class="p">)</span></span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">test</span> <span class="s2">"should redirect edit when logged in as wrong user"</span> <span class="k">do</span>
<span class="n">log_in_as</span><span class="p">(</span><span class="vi">@other_user</span><span class="p">)</span>
<span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
<span class="n">assert</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="n">root_url</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"should redirect update when logged in as wrong user"</span> <span class="k">do</span>
<span class="n">log_in_as</span><span class="p">(</span><span class="vi">@other_user</span><span class="p">)</span>
<span class="n">patch</span> <span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">),</span> <span class="ss">params: </span><span class="p">{</span> <span class="ss">user: </span><span class="p">{</span> <span class="ss">name: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">name</span><span class="p">,</span>
<span class="ss">email: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">email</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="n">root_url</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>为了重定向试图编辑其他用户资料的用户,我们要定义一个名为 <code>correct_user</code> 的方法,然后设定一个前置过滤器调用这个方法,如<a class="xref-link" href="#listing-correct-user-before-filter">代码清单 10.25</a> 所示。注意,<code>correct_user</code> 中定义了 <code>@user</code> 变量,所以可以把 <code>edit</code> 和 <code>update</code> 动作中的 <code>@user</code> 赋值语句删掉。</p>
<div id="listing-correct-user-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 10.25</span>:保护 <code>edit</code> 和 <code>update</code> 动作的 <code>correct_user</code> 前置过滤器 <span class="green">GREEN</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="n">before_action</span> <span class="ss">:logged_in_user</span><span class="p">,</span> <span class="ss">only: </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="hll"> <span class="n">before_action</span> <span class="ss">:correct_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span></span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">def</span> <span class="n">edit</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">update</span>
<span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Profile updated"</span>
<span class="n">redirect_to</span> <span class="vi">@user</span>
<span class="k">else</span>
<span class="n">render</span> <span class="s1">'edit'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span>
<span class="ss">:password_confirmation</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># 前置过滤器</span>
<span class="c1"># 确保用户已登录</span>
<span class="k">def</span> <span class="nf">logged_in_user</span>
<span class="k">unless</span> <span class="n">logged_in?</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Please log in."</span>
<span class="n">redirect_to</span> <span class="n">login_url</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="c1"># 确保是正确的用户</span>
<span class="k">def</span> <span class="nf">correct_user</span>
<span class="hll"> <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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></span>
<span class="hll"> <span class="n">redirect_to</span><span class="p">(</span><span class="n">root_url</span><span class="p">)</span> <span class="k">unless</span> <span class="vi">@user</span> <span class="o">==</span> <span class="n">current_user</span></span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>现在,测试组件应该可以通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.26</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<p>最后,我们还要重构一下。我们要遵守一般的约定,定义 <code>current_user?</code> 方法,返回布尔值,然后在 <code>correct_user</code> 中调用。我们要在 <code>Sessions</code> 辅助模块中定义这个方法,如<a class="xref-link" href="#listing-current-user-p">代码清单 10.27</a> 所示。 然后我们就可以把</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="k">unless</span> <span class="vi">@user</span> <span class="o">==</span> <span class="n">current_user</span>
</code></pre></div>
</div>
<p>改成意义稍微明确一点儿的</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="k">unless</span> <span class="n">current_user?</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
</code></pre></div>
</div>
<div id="listing-current-user-p" data-type="listing">
<h5><span class="title-label">代码清单 10.27</span>:<code>current_user?</code> 方法</h5>
<div class="source-file">app/helpers/sessions_helper.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">module</span> <span class="nn">SessionsHelper</span>
<span class="c1"># 登入指定的用户</span>
<span class="k">def</span> <span class="nf">log_in</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="n">session</span><span class="p">[</span><span class="ss">:user_id</span><span class="p">]</span> <span class="o">=</span> <span class="n">user</span><span class="p">.</span><span class="nf">id</span>
<span class="k">end</span>
<span class="c1"># 在持久会话中记住用户</span>
<span class="k">def</span> <span class="nf">remember</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="n">user</span><span class="p">.</span><span class="nf">remember</span>
<span class="n">cookies</span><span class="p">.</span><span class="nf">permanent</span><span class="p">.</span><span class="nf">signed</span><span class="p">[</span><span class="ss">:user_id</span><span class="p">]</span> <span class="o">=</span> <span class="n">user</span><span class="p">.</span><span class="nf">id</span>
<span class="n">cookies</span><span class="p">.</span><span class="nf">permanent</span><span class="p">[</span><span class="ss">:remember_token</span><span class="p">]</span> <span class="o">=</span> <span class="n">user</span><span class="p">.</span><span class="nf">remember_token</span>
<span class="k">end</span>
<span class="c1"># 如果指定用户是当前用户,返回 true</span>
<span class="k">def</span> <span class="nf">current_user?</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="hll"> <span class="n">user</span> <span class="o">==</span> <span class="n">current_user</span></span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>把直接比较的代码换成返回布尔值的方法后,得到的代码如<a class="xref-link" href="#listing-correct-user-before-filter-boolean">代码清单 10.28</a> 所示。</p>
<div id="listing-correct-user-before-filter-boolean" data-type="listing">
<h5><span class="title-label">代码清单 10.28</span>:<code>correct_user</code> 前置过滤器的最终版本 <span class="green">GREEN</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="n">before_action</span> <span class="ss">:logged_in_user</span><span class="p">,</span> <span class="ss">only: </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="n">before_action</span> <span class="ss">:correct_user</span><span class="p">,</span> <span class="ss">only: </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="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">def</span> <span class="n">edit</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">update</span>
<span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Profile updated"</span>
<span class="n">redirect_to</span> <span class="vi">@user</span>
<span class="k">else</span>
<span class="n">render</span> <span class="s1">'edit'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span>
<span class="ss">:password_confirmation</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># 前置过滤器</span>
<span class="c1"># 确保用户已登录</span>
<span class="k">def</span> <span class="nf">logged_in_user</span>
<span class="k">unless</span> <span class="n">logged_in?</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Please log in."</span>
<span class="n">redirect_to</span> <span class="n">login_url</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="c1"># 确保是正确的用户</span>
<span class="k">def</span> <span class="nf">correct_user</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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>
<span class="hll"> <span class="n">redirect_to</span><span class="p">(</span><span class="n">root_url</span><span class="p">)</span> <span class="k">unless</span> <span class="n">current_user?</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span></span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<h5 id="exercises-requiring-the-right-user" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>为什么要保护 <code>edit</code> 和 <code>update</code> 两个动作?</p>
</li>
<li>
<p>哪个动作在浏览器中容易测试?</p>
</li>
</ol>
</section>
<section data-type="sect2" id="friendly-forwarding">
<h2><span class="title-label">10.2.3</span> 友好的转向</h2>
<p>网站的权限系统完成了,但是还有一个小瑕疵:不管用户尝试访问的是哪个受保护的页面,登录后都会重定向到资料页面。也就是说,如果未登录的用户访问了编辑资料页面,网站要求先登录,登录后会重定向到 /users/1,而不是 /users/1/edit。如果登录后能重定向到用户之前想访问的页面就更好了。</p>
<p>实现这种需求所需的应用代码有点儿复杂,不过测试很简单,我们只需把<a class="xref-link" href="#listing-edit-tests-logged-in">代码清单 10.17</a> 中登录和访问编辑页面两个操作调换顺序即可。如<a class="xref-link" href="#listing-friendly-forwarding-test">代码清单 10.29</a> 所示,最终写出的测试先访问编辑页面,然后登录,最后确认把用户重定向到了编辑页面,而不是默认的资料页面。</p>
<div id="listing-friendly-forwarding-test" data-type="listing">
<h5><span class="title-label">代码清单 10.29</span>:测试友好的转向 <span class="red">RED</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UsersEditTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="hll"> <span class="nf">test</span> <span class="s2">"successful edit with friendly forwarding"</span> <span class="k">do</span></span>
<span class="hll"> <span class="n">get</span> <span class="n">edit_user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span></span>
<span class="hll"> <span class="n">log_in_as</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span></span>
<span class="hll"> <span class="n">assert_redirected_to</span> <span class="n">edit_user_url</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span></span>
<span class="nb">name</span> <span class="o">=</span> <span class="s2">"Foo Bar"</span>
<span class="n">email</span> <span class="o">=</span> <span class="s2">"[email protected]"</span>
<span class="n">patch</span> <span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">),</span> <span class="ss">params: </span><span class="p">{</span> <span class="ss">user: </span><span class="p">{</span> <span class="ss">name: </span><span class="nb">name</span><span class="p">,</span>
<span class="ss">email: </span><span class="n">email</span><span class="p">,</span>
<span class="ss">password: </span><span class="s2">""</span><span class="p">,</span>
<span class="ss">password_confirmation: </span><span class="s2">""</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="vi">@user</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">reload</span>
<span class="n">assert_equal</span> <span class="nb">name</span><span class="p">,</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">name</span>
<span class="n">assert_equal</span> <span class="n">email</span><span class="p">,</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">email</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>有了一个失败测试,现在可以实现友好的转向了。<sup>[<a id="fn-ref-5" href="#fn-5">5</a>]</sup>要转向用户真正想访问的页面,我们要在某个地方存储页面的地址,登录后再重定向到那个页面。我们将通过两个方法来实现这个过程,<code>store_location</code> 和 <code>redirect_back_or</code>,它们都在 <code>Sessions</code> 辅助模块中定义,如<a class="xref-link" href="#listing-friendly-forwarding-code">代码清单 10.30</a> 所示。</p>
<div id="listing-friendly-forwarding-code" data-type="listing">
<h5><span class="title-label">代码清单 10.30</span>:实现友好的转向 <span class="red">RED</span></h5>
<div class="source-file">app/helpers/sessions_helper.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">module</span> <span class="nn">SessionsHelper</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="o">.</span>
<span class="c1"># 重定向到存储的地址或者默认地址</span>
<span class="k">def</span> <span class="nf">redirect_back_or</span><span class="p">(</span><span class="n">default</span><span class="p">)</span>
<span class="n">redirect_to</span><span class="p">(</span><span class="n">session</span><span class="p">[</span><span class="ss">:forwarding_url</span><span class="p">]</span> <span class="o">||</span> <span class="n">default</span><span class="p">)</span>
<span class="n">session</span><span class="p">.</span><span class="nf">delete</span><span class="p">(</span><span class="ss">:forwarding_url</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># 存储后面需要使用的地址</span>
<span class="k">def</span> <span class="nf">store_location</span>
<span class="n">session</span><span class="p">[</span><span class="ss">:forwarding_url</span><span class="p">]</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="nf">original_url</span> <span class="k">if</span> <span class="n">request</span><span class="p">.</span><span class="nf">get?</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>我们使用 <code>session</code> 存储转向地址,这与 <a class="xref-link" href="chapter8.html#the-log-in-method">8.2.1 节</a>登入用户的方式类似。<a class="xref-link" href="#listing-friendly-forwarding-code">代码清单 10.30</a> 还用到了 <code>request</code> 对象,获取所请求页面的地址(<code>request.original_url</code>)。</p>
<p>在 <code>store_location</code> 方法中,把请求的地址存储在 <code>session[:forwarding_url]</code> 中,而且只当请求是 <code>GET</code> 请求时才存储。这么做,当未登录的用户提交表单时,不会存储转向地址(这种情况虽然罕见,但在提交表单前,如果用户手动删除了会话,还是会发生的)。如果存储了,那么本来期望接收 <code>POST</code>、<code>PATCH</code> 或 <code>DELETE</code> 请求的动作实际收到的是 <code>GET</code> 请求,从而导致错误。加上 <code>if request.get?</code> 能避免这种问题。<sup>[<a id="fn-ref-6" href="#fn-6">6</a>]</sup></p>
<p>若想使用 <code>store_location</code> 方法,我们要把它加入 <code>logged_in_user</code> 前置过滤器中,如<a class="xref-link" href="#listing-add-store-location">代码清单 10.31</a> 所示。</p>
<div id="listing-add-store-location" data-type="listing">
<h5><span class="title-label">代码清单 10.31</span>:把 <code>store_location</code> 方法添加到 <code>logged_in_user</code> 前置过滤器中 <span class="red">RED</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="n">before_action</span> <span class="ss">:logged_in_user</span><span class="p">,</span> <span class="ss">only: </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="n">before_action</span> <span class="ss">:correct_user</span><span class="p">,</span> <span class="ss">only: </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="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">def</span> <span class="n">edit</span>
<span class="k">end</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span>
<span class="ss">:password_confirmation</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># 前置过滤器</span>
<span class="c1"># 确保用户已登录</span>
<span class="k">def</span> <span class="nf">logged_in_user</span>
<span class="k">unless</span> <span class="n">logged_in?</span>
<span class="hll"> <span class="n">store_location</span></span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Please log in."</span>