-
Notifications
You must be signed in to change notification settings - Fork 11
/
chapter9.html
1987 lines (1695 loc) · 188 KB
/
chapter9.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 教程 - 第 9 章 更新,显示和删除用户</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.1.beta.3"/>
<link rel="stylesheet" type="text/css" href="http://cdn.staticfile.org/twitter-bootstrap/3.2.0/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" type="text/css" href="assets/style.css"/>
<script type="text/javascript" src="http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.staticfile.org/twitter-bootstrap/3.2.0/js/collapse.min.js"></script>
<script type="text/javascript" src="assets/global.js"></script>
</head>
<body>
<header class="navbar navbar-default navbar-fixed-top navbar-book">
<div class="container">
<div class="navbar-header">
<a href="http://railstutorial-china.org" class="navbar-brand">Ruby on Rails 教程</a>
<button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target=".book-navbar-collapse">
<span class="sr-only">导航</span>
<i class="fa fa-bars"></i>
</button>
<a href="http://railstutorial-china.org/#purchase" id="navbar-purchase-xs" class="btn btn-warning navbar-btn visible-xs collapsed-purchase-btn">购买</a>
</div>
<nav class="collapse navbar-collapse book-navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="http://railstutorial-china.org" title="首页">首页</a></li>
<li class="active"><a href="http://railstutorial-china.org/read/" title="在线阅读">阅读</a></li>
<li><a href="http://railstutorial-china.org/blog/" title="最新消息">博客</a></li>
<li><a href="https://selfstore.io/products/189/topics" title="论坛">论坛</a></li>
<li class="hidden-xs"><div><a href="http://railstutorial-china.org/#purchase" id="navbar-purchase" class="btn btn-warning navbar-btn" title="购买电子书">购买</a></div></li>
</ul>
</nav>
</div>
</header>
<div class="content">
<div class="container">
<div class="row">
<div class="col-lg-offset-2 col-lg-8">
<div class="alert alert-warning">
<p>在线版的内容可能落后于电子书,如果想及时获得更新,请<a href="http://railstutorial-china.org/#purchase" title="购买电子书">购买电子书</a>。</p>
</div>
<article class="article">
<section data-type="chapter" id="updating-showing-and-deleting-users">
<h1><span class="title-label">第 9 章</span> 更新,显示和删除用户</h1>
<p>本章我们要完成用户资源的 REST 动作(<a href="chapter7.html#table-restful-users">表 7.1</a>),添加 <code>edit</code>、<code>update</code>、<code>index</code> 和 <code>destroy</code> 动作。首先我们要实现更新用户个人资料的功能,并借此实现权限机制(基于<a href="chapter8.html#log-in-log-out">第 8 章</a>实现的认证系统)。然后要创建一个页面,列出所有用户(也需要认证),期间会介绍如何使用示例数据和分页。最后,我们还要实现删除用户的功能,从数据库中删除用户记录。我们不会为所有用户都提供这种强大的功能,而是创建管理员,授权他们来删除用户。</p>
<section data-type="sect1" id="updating-users">
<h1><span class="title-label">9.1</span> 更新用户</h1>
<p>编辑用户信息的方法和创建新用户差不多(参见<a 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 href="chapter3.html#aside-get-etc">旁注 3.2</a>)。二者之间最大的区别是,任何人都可以注册,但只有当前用户才能更新自己的信息。我们可以使用<a href="chapter8.html#log-in-log-out">第 8 章</a>实现的认证机制,通过“事前过滤器”(before filter)实现访问限制。</p>
<p>开始实现之前,我们先切换到 <code>updating-users</code> 主题分支:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>git checkout master
<span class="nv">$ </span>git checkout -b updating-users
</pre></div>
</div>
<section data-type="sect2" id="edit-form">
<h2><span class="title-label">9.1.1</span> 编辑表单</h2>
<p>我们先来创建编辑表单,构思图如<a href="#fig-edit-user-mockup">图 9.1</a>。<sup>[<a id="fn-ref-1" href="#fn-1">1</a>]</sup>要把这个构思图转换成可以使用的页面,我们既要编写用户控制器的 <code>edit</code> 动作,也要创建编辑用户的视图。我们先来编写 <code>edit</code> 动作。在 <code>edit</code> 动作中我们要从数据库中读取相应的用户。由<a href="chapter7.html#table-restful-users">表 7.1</a> 得知,用户的编辑页面地址是 /users/1/edit(假设用户的 ID 是 1)。我们知道用户的 ID 可以使用 <code>params[:id]</code> 获取,那么就可以使用<a href="#listing-initial-edit-action">代码清单 9.1</a> 中的代码查找用户。</p>
<div id="listing-initial-edit-action" data-type="listing">
<h5><span class="title-label">代码清单 9.1</span>:用户控制器的 <code>edit</code> 动作</h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</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="o">.</span><span class="n">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="o">.</span><span class="n">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="o">.</span><span class="n">save</span>
<span class="n">log_in</span> <span class="vi">@user</span>
<span class="n">flash</span><span class="o">[</span><span class="ss">:success</span><span class="o">]</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</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="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span><span class="o">.</span><span class="n">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>
</pre></div>
</div>
<div id="fig-edit-user-mockup" class="figure"><img src="images/chapter9/edit_user_mockup_bootstrap.png" alt="edit user mockup bootstrap" /><div class="figcaption"><span class="title-label">图 9.1</span>:用户编辑页面的构思图</div></div>
<p>用户编辑页面的视图(要手动创建这个文件)如<a href="#listing-user-edit-view">代码清单 9.2</a> 所示。注意,这个视图和<a href="chapter7.html#listing-signup-form">代码清单 7.13</a> 中新建用户的视图很相似,有很多重复的代码,所以可以重构,把共用的代码放到局部视图中,这个任务留作练习(<a href="#updating-showing-and-deleting-users-exercises">9.6 节</a>)。</p>
<div id="listing-user-edit-view" data-type="listing">
<h5><span class="title-label">代码清单 9.2</span>:用户编辑页面的视图</h5>
<div class="source-file">app/views/users/edit.html.erb</div>
<div class="highlight language-erb"><pre><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="x"></span>
<span class="x"><h1>Update your profile</h1></span>
<span class="x"><div class="row"></span>
<span class="x"> <div class="col-md-6 col-md-offset-3"></span>
<span class="x"> </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="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">render</span> <span class="s1">'shared/error_messages'</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">label</span> <span class="ss">:name</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">text_field</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">class</span><span class="p">:</span> <span class="s1">'form-control'</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">label</span> <span class="ss">:email</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">email_field</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">class</span><span class="p">:</span> <span class="s1">'form-control'</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">label</span> <span class="ss">:password</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">password_field</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">class</span><span class="p">:</span> <span class="s1">'form-control'</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">label</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="s2">"Confirmation"</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">password_field</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="ss">class</span><span class="p">:</span> <span class="s1">'form-control'</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">f</span><span class="o">.</span><span class="n">submit</span> <span class="s2">"Save changes"</span><span class="p">,</span> <span class="ss">class</span><span class="p">:</span> <span class="s2">"btn btn-primary"</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </span><span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> <div class="gravatar_edit"></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="n">gravatar_for</span> <span class="vi">@user</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> <a href="http://gravatar.com/emails" target="_blank">change</a></span>
<span class="x"> </div></span>
<span class="x"> </div></span>
<span class="x"></div></span>
</pre></div>
</div>
<p>这里再次用到了 <a href="chapter7.html#signup-error-messages">7.3.3 节</a>创建的 <code>error_messages</code> 局部视图。顺便说一下,修改 Gravatar 头像的链接用到了 <code>target="_blank"</code>,目的是在新窗口或选项卡中打开这个网页。链接到第三方网站时一般都会这么做。</p>
<p><a href="#listing-initial-edit-action">代码清单 9.1</a> 中定义了 <code>@user</code> 实例变量,所以编辑页面可以正确渲染,如<a href="#fig-edit-page">图 9.2</a> 所示。从“Name”和“Email”字段可以看出,Rails 会自动使用 <code>@user</code> 变量的属性值填写相应的字段。</p>
<div id="fig-edit-page" class="figure"><img src="images/chapter9/edit_page_3rd_edition.png" alt="edit page 3rd edition" /><div class="figcaption"><span class="title-label">图 9.2</span>:编辑页面初始版本,名字和电子邮件地址自动填入了值</div></div>
<p>查看用户编辑页面的 HTML 源码,会看到预期的表单标签,如<a href="#listing-edit-form-html">代码清单 9.3</a> 所示(某些细节可能不同)。</p>
<div id="listing-edit-form-html" data-type="listing">
<h5><span class="title-label">代码清单 9.3</span>:<a href="#listing-user-edit-view">代码清单 9.2</a> 定义的编辑表单生成的 HTML</h5>
<div class="highlight language-html"><pre><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>
</pre></div>
</div>
<p>留意一下这个隐藏字段:</p>
<div data-type="listing">
<div class="highlight language-html"><pre><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>
</pre></div>
</div>
<p>因为浏览器并不支持发送 <code>PATCH</code> 请求(<a 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 href="#listing-user-edit-view">代码清单 9.2</a> 和<a href="chapter7.html#listing-signup-form">代码清单 7.13</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><span class="go">$ rails console</span>
<span class="gp">>> </span><span class="no">User</span><span class="o">.</span><span class="n">new</span><span class="o">.</span><span class="n">new_record?</span>
<span class="go">=> true</span>
<span class="gp">>> </span><span class="no">User</span><span class="o">.</span><span class="n">first</span><span class="o">.</span><span class="n">new_record?</span>
<span class="go">=> false</span>
</pre></div>
</div>
<p>所以使用 <code>form_for(@user)</code> 构建表单时,如果 <code>@user.new_record?</code> 返回 <code>true</code>,发送 <code>POST</code> 请求,否则发送 <code>PATCH</code> 请求。</p>
<p>最后,我们要把导航中指向编辑用户页面的链接换成真实的地址。很简单,我们直接使用<a href="chapter7.html#table-restful-users">表 7.1</a> 中列出的 <code>edit_user_path</code> 具名路由,并把参数设为<a href="chapter8.html#listing-persistent-current-user">代码清单 8.36</a> 中定义的 <code>current_user</code> 辅助方法:</p>
<div data-type="listing">
<div class="highlight language-erb"><pre><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="x"></span>
</pre></div>
</div>
<p>完整的视图如<a href="#listing-settings-link">代码清单 9.4</a> 所示。</p>
<div id="listing-settings-link" data-type="listing">
<h5><span class="title-label">代码清单 9.4</span>:在网站布局中设置“Settings”链接的地址</h5>
<div class="source-file">app/views/layouts/_header.html.erb</div>
<div class="highlight language-erb"><pre><span class="x"><header class="navbar navbar-fixed-top navbar-inverse"></span>
<span class="x"> <div class="container"></span>
<span class="x"> </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="nb">id</span><span class="p">:</span> <span class="s2">"logo"</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> <nav></span>
<span class="x"> <ul class="nav navbar-nav navbar-right"></span>
<span class="x"> <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="x"></li></span>
<span class="x"> <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="x"></li></span>
<span class="x"> </span><span class="cp"><%</span> <span class="k">if</span> <span class="n">logged_in?</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> <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="x"></li></span>
<span class="x"> <li class="dropdown"></span>
<span class="x"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"></span>
<span class="x"> Account <b class="caret"></b></span>
<span class="x"> </a></span>
<span class="x"> <ul class="dropdown-menu"></span>
<span class="x"> <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="x"></li></span>
<span class="hll"><span class="x"> <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="x"></li></span>
</span><span class="x"> <li class="divider"></li></span>
<span class="x"> <li></span>
<span class="x"> </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="nb">method</span><span class="p">:</span> <span class="s2">"delete"</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </li></span>
<span class="x"> </ul></span>
<span class="x"> </li></span>
<span class="x"> </span><span class="cp"><%</span> <span class="k">else</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> <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="x"></li></span>
<span class="x"> </span><span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span><span class="x"></span>
<span class="x"> </ul></span>
<span class="x"> </nav></span>
<span class="x"> </div></span>
<span class="x"></header></span>
</pre></div>
</div>
</section>
<section data-type="sect2" id="unsuccessful-edits">
<h2><span class="title-label">9.1.2</span> 编辑失败</h2>
<p>本节我们要处理编辑失败的情况,过程和处理注册失败差不多(<a href="chapter7.html#unsuccessful-signups">7.3 节</a>)。我们要先定义 <code>update</code> 动作,把提交的 <code>params</code> 哈希传给 <code>update_attributes</code> 方法(<a href="chapter6.html#updating-user-objects">6.1.5 节</a>),更新用户,如<a href="#listing-user-update-action-unsuccessful">代码清单 9.5</a> 所示。如果提交的数据无效,更新操作会返回 <code>false</code>,由 <code>else</code> 分支处理,重新渲染编辑页面。我们之前用过类似的处理方式,代码结构和第一个版本的 <code>create</code> 动作类似(<a href="chapter7.html#listing-first-create-action">代码清单 7.16</a>)。</p>
<div id="listing-user-update-action-unsuccessful" data-type="listing">
<h5><span class="title-label">代码清单 9.5</span>:<code>update</code> 动作初始版本</h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</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="o">.</span><span class="n">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="o">.</span><span class="n">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="o">.</span><span class="n">save</span>
</span> <span class="n">log_in</span> <span class="vi">@user</span>
<span class="n">flash</span><span class="o">[</span><span class="ss">:success</span><span class="o">]</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
<span class="hll"> <span class="k">if</span> <span class="vi">@user</span><span class="o">.</span><span class="n">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="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span><span class="o">.</span><span class="n">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>
</pre></div>
</div>
<p>注意在调用 <code>update_attributes</code> 方法时指定的 <code>user_params</code> 参数,这种用法是“健壮参数”(strong parameter),可以避免批量赋值带来的安全隐患(参见 <a href="chapter7.html#strong-parameters">7.3.2 节</a>)。</p>
<p>因为用户模型中定义了验证规则,而且<a href="#listing-user-edit-view">代码清单 9.2</a> 中渲染了错误消息局部视图,所以提交无效信息后会显示一些有用的错误消息,如<a href="#fig-buggy-edit-with-invalid-information">图 9.3</a> 所示。</p>
<div id="fig-buggy-edit-with-invalid-information" class="figure"><img src="images/chapter9/edit_with_invalid_information_3rd_edition.png" alt="edit with invalid information 3rd edition" /><div class="figcaption"><span class="title-label">图 9.3</span>:提交编辑表单后显示的错误消息</div></div>
</section>
<section data-type="sect2" id="testing-unsuccessful-edits">
<h2><span class="title-label">9.1.3</span> 编辑失败的测试</h2>
<p><a href="#unsuccessful-edits">9.1.2 节</a>结束时编辑表单已经可以使用,按照<a href="chapter3.html#aside-when-to-test">旁注 3.3</a> 中的测试指导方针,现在我们要编写集成测试捕获回归。和之前一样,首先要生成一个集成测试文件:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>rails generate integration_test users_edit
invoke test_unit
create <span class="nb">test</span>/integration/users_edit_test.rb
</pre></div>
</div>
<p>然后为编辑失败编写一个简单的测试,如<a href="#listing-unsuccessful-edit-test">代码清单 9.6</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">代码清单 9.6</span>:编辑失败的测试 <span class="green">GREEN</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><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">patch</span> <span class="n">user_path</span><span class="p">(</span><span class="vi">@user</span><span class="p">),</span> <span class="ss">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="s1">''</span><span class="p">,</span>
<span class="ss">email</span><span class="p">:</span> <span class="s1">'foo@invalid'</span><span class="p">,</span>
<span class="ss">password</span><span class="p">:</span> <span class="s1">'foo'</span><span class="p">,</span>
<span class="ss">password_confirmation</span><span class="p">:</span> <span class="s1">'bar'</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>
</pre></div>
</div>
<p>此时,测试组件应该可以通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.7</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
</section>
<section data-type="sect2" id="successful-edits">
<h2><span class="title-label">9.1.4</span> 编辑成功(使用 TDD)</h2>
<p>现在我们要让编辑表单能正常使用。编辑头像的功能已经有了,因为我们把上传头像的操作交由 Gravatar 处理,如需更换头像,点击<a href="#fig-edit-page">图 9.2</a> 中的“change”链接就可以了,如<a href="#fig-gravatar-cropper">图 9.4</a> 所示。下面我们来实现编辑其他信息的功能。</p>
<div id="fig-gravatar-cropper" class="figure"><img src="images/chapter9/gravatar_cropper.png" alt="gravatar cropper" /><div class="figcaption"><span class="title-label">图 9.4</span>:Gravatar 的图片剪切界面,上传了一个<a href="http://www.michaelhartl.com/">帅哥</a>的图片</div></div>
<p>上手测试后,你可能会发现,编写应用代码之前编写测试比之后再写更有用。针对现在这种情况,我们要编写的是“验收测试”(acceptance test),由测试的结果决定某个功能是否完成。为了演示如何编写验收测试,我们要使用测试驱动开发技术完成用户编辑功能。</p>
<p>我们要编写类似<a href="#listing-unsuccessful-edit-test">代码清单 9.6</a> 中的测试,确认更新用户的操作表现正确,只不过这一次我们会提交有效的信息。然后检查显示了闪现消息,而且成功重定向到了用户的资料页面,同时还要确认数据库中保存的用户信息也正确更新了。这个测试如<a href="#listing-successful-edit-test">代码清单 9.8</a> 所示。注意,在<a href="#listing-successful-edit-test">代码清单 9.8</a> 中,密码和密码确认都为空值,因为修改用户名和电子邮件地址时并不想修改密码。还要注意,我们使用 <code>@user.reload</code>(<a 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">代码清单 9.8</span>:编辑成功的测试 <span class="red">RED</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="nb">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="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">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="nb">name</span><span class="p">,</span>
<span class="ss">email</span><span class="p">:</span> <span class="n">email</span><span class="p">,</span>
<span class="ss">password</span><span class="p">:</span> <span class="s2">""</span><span class="p">,</span>
<span class="ss">password_confirmation</span><span class="p">:</span> <span class="s2">""</span> <span class="p">}</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="o">.</span><span class="n">empty?</span>
<span class="n">assert_redirected_to</span> <span class="vi">@user</span>
<span class="vi">@user</span><span class="o">.</span><span class="n">reload</span>
<span class="n">assert_equal</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="nb">name</span>
<span class="n">assert_equal</span> <span class="vi">@user</span><span class="o">.</span><span class="n">email</span><span class="p">,</span> <span class="n">email</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>要让<a href="#listing-successful-edit-test">代码清单 9.8</a> 中的测试通过,我们可以参照最终版 <code>create</code> 动作(<a href="chapter8.html#listing-login-upon-signup">代码清单 8.22</a>)来编写 <code>update</code> 动作,如<a href="#listing-user-update-action">代码清单 9.9</a> 所示。</p>
<div id="listing-user-update-action" data-type="listing">
<h5><span class="title-label">代码清单 9.9</span>:用户控制器的 <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><span class="k">class</span> <span class="nc">UsersController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
<span class="k">if</span> <span class="vi">@user</span><span class="o">.</span><span class="n">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="o">[</span><span class="ss">:success</span><span class="o">]</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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>如<a href="#listing-user-update-action">代码清单 9.9</a> 的标题所示,测试组件无法通过,因为密码长度验证(<a href="chapter6.html#listing-password-implementation">代码清单 6.39</a>)失败了,这是因为<a href="#listing-successful-edit-test">代码清单 9.8</a> 中密码和密码确认都是空值。为了让测试通过,我们要在密码为空值时特殊处理最短长度验证,方法是把 <code>allow_nil: true</code> 参数传给 <code>validates</code> 方法,如<a href="#listing-allow-blank-password">代码清单 9.10</a> 所示。</p>
<div id="listing-allow-blank-password" data-type="listing">
<h5><span class="title-label">代码清单 9.10</span>:更新时允许密码为空 <span class="green">GREEN</span></h5>
<div class="source-file">app/models/user.rb</div>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="kp">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="o">.</span><span class="n">email</span> <span class="o">=</span> <span class="n">email</span><span class="o">.</span><span class="n">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="p">:</span> <span class="kp">true</span><span class="p">,</span> <span class="ss">length</span><span class="p">:</span> <span class="p">{</span> <span class="ss">maximum</span><span class="p">:</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="p">:</span> <span class="kp">true</span><span class="p">,</span> <span class="ss">length</span><span class="p">:</span> <span class="p">{</span> <span class="ss">maximum</span><span class="p">:</span> <span class="mi">255</span> <span class="p">}</span>
<span class="nb">format</span><span class="p">:</span> <span class="p">{</span> <span class="ss">with</span><span class="p">:</span> <span class="no">VALID_EMAIL_REGEX</span> <span class="p">},</span>
<span class="ss">uniqueness</span><span class="p">:</span> <span class="p">{</span> <span class="ss">case_sensitive</span><span class="p">:</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="p">:</span> <span class="kp">true</span><span class="p">,</span> <span class="ss">length</span><span class="p">:</span> <span class="p">{</span> <span class="ss">minimum</span><span class="p">:</span> <span class="mi">6</span> <span class="p">},</span> <span class="ss">allow_nil</span><span class="p">:</span> <span class="kp">true</span>
</span> <span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>你可能担心这么改用户注册时可以把密码设为空值,其实不然,<a 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 href="chapter7.html#signup-error-messages">7.3.3 节</a>提到的错误消息重复问题。)</p>
<p>至此,用户编辑页面应该可以正常使用了,如<a href="#fig-edit-form-working">图 9.5</a> 所示。你也可以运行测试组件确认一下,应该可以通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.11</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
<div id="fig-edit-form-working" class="figure"><img src="images/chapter9/edit_form_working.png" alt="edit form working" /><div class="figcaption"><span class="title-label">图 9.5</span>:编辑成功后显示的页面</div></div>
</section>
</section>
<section data-type="sect1" id="authorization">
<h1><span class="title-label">9.2</span> 权限系统</h1>
<p>在 Web 应用中,认证系统的功能是识别网站的用户,权限系统是控制用户可以做什么操作。<a href="chapter8.html#log-in-log-out">第 8 章</a>实现的认证机制有一个很好的作用,可以实现权限系统。</p>
<p>虽然 <a href="#updating-users">9.1 节</a>已经完成了 <code>edit</code> 和 <code>update</code> 动作,但是却有一个荒唐的安全隐患:任何人(甚至是未登录的用户)都可以访问这两个动作,而且登录后的用户可以更新所有其他用户的资料。本节我们要实现一种安全机制,限制用户必须先登录才能更新自己的资料,而且不能更新别人的资料。</p>
<p><a href="#requiring-logged-in-users">9.2.1 节</a>要处理未登录用户试图访问有权访问的保护页面。因为在使用应用的过程中经常会发生这种情况,所以我们要把这些用户转向登录页面,而且会显示一个帮助消息,构思图如<a href="#fig-login-page-protected-mockup">图 9.6</a> 所示。另一种情况是,用户尝试访问没有权限查看的页面(例如已登录的用户试图访问其他用户的编辑页面),此时要把用户重定向到根地址(<a href="#requiring-the-right-user">9.2.2 节</a>)。</p>
<div id="fig-login-page-protected-mockup" class="figure"><img src="images/chapter9/login_page_protected_mockup.png" alt="login page protected mockup" /><div class="figcaption"><span class="title-label">图 9.6</span>:访问受保护页面时看到的页面构思图</div></div>
<section data-type="sect2" id="requiring-logged-in-users">
<h2><span class="title-label">9.2.1</span> 必须先登录</h2>
<p>为了实现<a href="#fig-login-page-protected-mockup">图 9.6</a> 中的转向功能,我们要在用户控制器中使用“事前过滤器”。事前过滤器通过 <code>before_action</code> 方法设定,指定在某个动作运行前调用一个方法。<sup>[<a id="fn-ref-3" href="#fn-3">3</a>]</sup>为了实现要求用户先登录的限制,我们要定义一个名为 <code>logged_in_user</code> 的方法,然后使用 <code>before_action :logged_in_user</code> 调用这个方法,如<a href="#listing-authorize-before-filter">代码清单 9.12</a> 所示。</p>
<div id="listing-authorize-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 9.12</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><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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</span>
</span> <span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span><span class="o">.</span><span class="n">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="o">[</span><span class="ss">:danger</span><span class="o">]</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>
</pre></div>
</div>
<p>默认情况下,事前过滤器会应用于控制器中的所有动作,所以在上述代码中我们传入了 <code>:only</code> 参数,指定只应用在 <code>edit</code> 和 <code>update</code> 动作上。</p>
<p>退出后再访问用户编辑页面 <a href="http://localhost:3000/users/1/edit">/users/1/edit</a>,可以看到这个事前过滤器的效果,如<a href="#fig-protected-log-in">图 9.7</a> 所示。</p>
<div id="fig-protected-log-in" class="figure"><img src="images/chapter9/protected_log_in_3rd_edition.png" alt="protected log in 3rd edition" /><div class="figcaption"><span class="title-label">图 9.7</span>:尝试访问受保护页面后显示的登录表单</div></div>
<p>如<a href="#listing-authorize-before-filter">代码清单 9.12</a> 的标题所示,现在测试组件无法通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.13</span>:<strong class="red">RED</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
<p>这是因为现在 <code>edit</code> 和 <code>update</code> 动作都需要用户先登录,而在相应的测试中没有已登录的用户。</p>
<p>所以,在测试访问 <code>edit</code> 和 <code>update</code> 动作之前,要先登入用户。这个操作可以通过 <a href="chapter8.html#remember-tests">8.4.6 节</a>定义的 <code>log_in_as</code> 辅助方法(<a href="chapter8.html#listing-test-helper-log-in">代码清单 8.50</a>)轻易实现,如<a href="#listing-edit-tests-logged-in">代码清单 9.14</a> 所示。</p>
<div id="listing-edit-tests-logged-in" data-type="listing">
<h5><span class="title-label">代码清单 9.14</span>:登入测试用户 <span class="green">GREEN</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>(可以把登入测试用户的代码放在 <code>setup</code> 方法中,去除一些重复。但是,在 <a href="#friendly-forwarding">9.2.3 节</a>我们要修改其中一个测试,在登录前访问编辑页面,如果把登录操作放在 <code>setup</code> 方法中就不能先访问其他页面了。)</p>
<p>现在,测试组件应该可以通过了:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.15</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
<p>测试组件虽然通过了,但是对事前过滤器的测试还没完,因为即便把安全防护去掉,测试也能通过。你可以把事前过滤器注释掉确认一下,如<a href="#listing-commented-out-before-filter">代码清单 9.16</a> 所示。这可不妙。在测试组件能捕获的所有回归中,重大安全漏洞或许是最重要的。按照<a href="#listing-commented-out-before-filter">代码清单 9.16</a> 的方式修改后,测试绝对不能通过。下面我们编写测试捕获这个问题。</p>
<div id="listing-commented-out-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 9.16</span>:注释掉事前过滤器,测试安全防护措施 <span class="green">GREEN</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>事前过滤器应用在指定的各个动作上,因此我们要在用户控制器的测试中编写相应的测试。我们计划使用正确的请求方法访问 <code>edit</code> 和 <code>update</code> 动作,然后确认把用户重定向到了登录地址。由<a href="chapter7.html#table-restful-users">表 7.1</a> 得知,正确的请求方法分别是 <code>GET</code> 和 <code>PATCH</code>,所以在测试中要使用 <code>get</code> 和 <code>patch</code>,如<a href="#listing-edit-update-redirect-tests">代码清单 9.17</a> 所示。</p>
<div id="listing-edit-update-redirect-tests" data-type="listing">
<h5><span class="title-label">代码清单 9.17</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><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">ActionController</span><span class="o">::</span><span class="no">TestCase</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="hll"> <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> <span class="k">end</span>
<span class="nb">test</span> <span class="s2">"should get new"</span> <span class="k">do</span>
<span class="n">get</span> <span class="ss">:new</span>
<span class="n">assert_response</span> <span class="ss">:success</span>
<span class="k">end</span>
<span class="hll"> <span class="nb">test</span> <span class="s2">"should redirect edit when not logged in"</span> <span class="k">do</span>
</span><span class="hll"> <span class="n">get</span> <span class="ss">:edit</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span>
</span><span class="hll"> <span class="n">assert_redirected_to</span> <span class="n">login_url</span>
</span><span class="hll"> <span class="k">end</span>
</span>
<span class="hll"> <span class="nb">test</span> <span class="s2">"should redirect update when not logged in"</span> <span class="k">do</span>
</span><span class="hll"> <span class="n">patch</span> <span class="ss">:update</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span><span class="p">,</span> <span class="ss">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="ss">email</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">email</span> <span class="p">}</span>
</span><span class="hll"> <span class="n">assert_redirected_to</span> <span class="n">login_url</span>
</span><span class="hll"> <span class="k">end</span>
</span><span class="k">end</span>
</pre></div>
</div>
<p>注意 <code>get</code> 和 <code>patch</code> 的参数:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">get</span> <span class="ss">:edit</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span>
</pre></div>
</div>
<p>和</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">patch</span> <span class="ss">:update</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span><span class="p">,</span> <span class="ss">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="ss">email</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">email</span> <span class="p">}</span>
</pre></div>
</div>
<p>这里使用了一个 Rails 约定:指定 <code>id: @user</code> 时,Rails 会自动使用 <code>@user.id</code>。在 <code>patch</code> 方法中还要指定一个 <code>user</code> 哈希,这样路由才能正常运行。(如果查看<a href="chapter2.html#a-toy-app">第 2 章</a>为玩具应用生成的用户控制器测试,会看到上述代码。)</p>
<p>测试组件现在无法通过,和我们预期的一样。为了让测试通过,我们只需把事前过滤器的注释去掉,如<a href="#listing-uncommented-before-filter">代码清单 9.18</a> 所示。</p>
<div id="listing-uncommented-before-filter" data-type="listing">
<h5><span class="title-label">代码清单 9.18</span>:去掉事前过滤器的注释 <span class="green">GREEN</span></h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</span>
</span> <span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>这样修改之后,测试组件应该可以通过了:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.19</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
<p>如果不小心让未授权的用户能访问 <code>edit</code> 动作,现在测试组件能立即捕获。</p>
</section>
<section data-type="sect2" id="requiring-the-right-user">
<h2><span class="title-label">9.2.2</span> 用户只能编辑自己的资料</h2>
<p>当然,要求用户必须先登录还不够,用户必须只能编辑自己的资料。由 <a href="#requiring-logged-in-users">9.2.1 节</a>得知,测试组件很容易漏掉基本的安全缺陷,所以我们要使用测试驱动开发技术确保写出的代码能正确实现安全机制。为此,我们要在用户控制器的测试中添加一些测试,完善<a href="#listing-edit-update-redirect-tests">代码清单 9.17</a>。</p>
<p>为了确保用户不能编辑其他用户的信息,我们需要登入第二个用户。所以,在用户固件文件中要再添加一个用户,如<a href="#listing-fixture-second-user">代码清单 9.20</a> 所示。</p>
<div id="listing-fixture-second-user" data-type="listing">
<h5><span class="title-label">代码清单 9.20</span>:在固件文件中添加第二个用户</h5>
<div class="source-file">test/fixtures/users.yml</div>
<div class="highlight language-yaml"><pre><span class="l-Scalar-Plain">michael</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Michael Example</span>
<span class="l-Scalar-Plain">email</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">[email protected]</span>
<span class="l-Scalar-Plain">password_digest</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= User.digest('password') %></span>
<span class="hll"><span class="l-Scalar-Plain">archer</span><span class="p-Indicator">:</span>
</span><span class="hll"> <span class="l-Scalar-Plain">name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Sterling Archer</span>
</span><span class="hll"> <span class="l-Scalar-Plain">email</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">[email protected]</span>
</span><span class="hll"> <span class="l-Scalar-Plain">password_digest</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= User.digest('password') %></span>
</span></pre></div>
</div>
<p>使用<a href="chapter8.html#listing-test-helper-log-in">代码清单 8.50</a> 中定义的 <code>log_in_as</code> 方法,我们可以使用<a href="#listing-edit-update-wrong-user-tests">代码清单 9.21</a> 中的代码测试 <code>edit</code> 和 <code>update</code> 动作。注意,这里没有重定向到登录地址,而是根地址,因为试图编辑其他用户资料的用户已经登录了。</p>
<div id="listing-edit-update-wrong-user-tests" data-type="listing">
<h5><span class="title-label">代码清单 9.21</span>:尝试编辑其他用户资料的测试 <span class="red">RED</span></h5>
<div class="source-file">test/controllers/users_controller_test.rb</div>
<div class="highlight language-ruby"><pre><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">ActionController</span><span class="o">::</span><span class="no">TestCase</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="nb">test</span> <span class="s2">"should get new"</span> <span class="k">do</span>
<span class="n">get</span> <span class="ss">:new</span>
<span class="n">assert_response</span> <span class="ss">:success</span>
<span class="k">end</span>
<span class="nb">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="ss">:edit</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</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="ss">:update</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span><span class="p">,</span> <span class="ss">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="ss">email</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">email</span> <span class="p">}</span>
<span class="n">assert_redirected_to</span> <span class="n">login_url</span>
<span class="k">end</span>
<span class="hll"> <span class="nb">test</span> <span class="s2">"should redirect edit when logged in as wrong user"</span> <span class="k">do</span>
</span><span class="hll"> <span class="n">log_in_as</span><span class="p">(</span><span class="vi">@other_user</span><span class="p">)</span>
</span><span class="hll"> <span class="n">get</span> <span class="ss">:edit</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span>
</span><span class="hll"> <span class="n">assert_redirected_to</span> <span class="n">root_url</span>
</span><span class="hll"> <span class="k">end</span>
</span>
<span class="hll"> <span class="nb">test</span> <span class="s2">"should redirect update when logged in as wrong user"</span> <span class="k">do</span>
</span><span class="hll"> <span class="n">log_in_as</span><span class="p">(</span><span class="vi">@other_user</span><span class="p">)</span>
</span><span class="hll"> <span class="n">patch</span> <span class="ss">:update</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="vi">@user</span><span class="p">,</span> <span class="ss">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="ss">email</span><span class="p">:</span> <span class="vi">@user</span><span class="o">.</span><span class="n">email</span> <span class="p">}</span>
</span><span class="hll"> <span class="n">assert_redirected_to</span> <span class="n">root_url</span>
</span><span class="hll"> <span class="k">end</span>
</span><span class="k">end</span>
</pre></div>
</div>
<p>为了重定向试图编辑其他用户资料的用户,我们要定义一个名为 <code>correct_user</code> 的方法,然后设定一个事前过滤器调用这个方法,如<a href="#listing-correct-user-before-filter">代码清单 9.22</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">代码清单 9.22</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><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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</span>
</span> <span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">def</span> <span class="nf">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="o">.</span><span class="n">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="n">flash</span><span class="o">[</span><span class="ss">:success</span><span class="o">]</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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span><span class="o">.</span><span class="n">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="o">[</span><span class="ss">:danger</span><span class="o">]</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</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>
</pre></div>
</div>
<p>现在,测试组件应该可以通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.23</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
<p>最后,我们还要重构一下。我们要遵守一般约定,定义 <code>current_user?</code> 方法,返回布尔值,然后在 <code>correct_user</code> 中调用。我们要在会话辅助方法模块中定义这个方法,如<a href="#listing-current-user-p">代码清单 9.24</a> 所示。 然后我们就可以把</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="k">unless</span> <span class="vi">@user</span> <span class="o">==</span> <span class="n">current_user</span>
</pre></div>
</div>
<p>改成意义稍微明确一点儿的</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="k">unless</span> <span class="n">current_user?</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
</pre></div>
</div>
<div id="listing-current-user-p" data-type="listing">
<h5><span class="title-label">代码清单 9.24</span>:<code>current_user?</code> 方法</h5>
<div class="source-file">app/helpers/sessions_helper.rb</div>
<div class="highlight language-ruby"><pre><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="o">[</span><span class="ss">:user_id</span><span class="o">]</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">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="o">.</span><span class="n">remember</span>
<span class="n">cookies</span><span class="o">.</span><span class="n">permanent</span><span class="o">.</span><span class="n">signed</span><span class="o">[</span><span class="ss">:user_id</span><span class="o">]</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">id</span>
<span class="n">cookies</span><span class="o">.</span><span class="n">permanent</span><span class="o">[</span><span class="ss">:remember_token</span><span class="o">]</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>把直接比较的代码换成返回布尔值的方法后,得到的代码如<a href="#listing-correct-user-before-filter-boolean">代码清单 9.25</a> 所示。</p>
<div id="listing-correct-user-before-filter-boolean" data-type="listing">
<h5><span class="title-label">代码清单 9.25</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><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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">def</span> <span class="nf">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="o">.</span><span class="n">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span>
<span class="n">flash</span><span class="o">[</span><span class="ss">:success</span><span class="o">]</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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span><span class="o">.</span><span class="n">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="o">[</span><span class="ss">:danger</span><span class="o">]</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</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>
</pre></div>
</div>
</section>
<section data-type="sect2" id="friendly-forwarding">
<h2><span class="title-label">9.2.3</span> 友好的转向</h2>
<p>网站的权限系统完成了,但是还有一个小瑕疵:不管用户尝试访问的是哪个受保护的页面,登录后都会重定向到资料页面。也就是说,如果未登录的用户访问了编辑资料页面,网站要求先登录,登录后会重定向到 /users/1,而不是 /users/1/edit。如果登录后能重定向到用户之前想访问的页面就更好了。</p>
<p>实现这种需求所需的应用代码有点儿复杂,不过测试很简单,我们只需把<a href="#listing-edit-tests-logged-in">代码清单 9.14</a> 中登录和访问编辑页面两个操作调换顺序即可。如<a href="#listing-friendly-forwarding-test">代码清单 9.26</a> 所示,最终写出的测试先访问编辑页面,然后登录,最后确认把用户重定向到了编辑页面,而不是资料页面。</p>
<div id="listing-friendly-forwarding-test" data-type="listing">
<h5><span class="title-label">代码清单 9.26</span>:测试友好的转向 <span class="red">RED</span></h5>
<div class="source-file">test/integration/users_edit_test.rb</div>
<div class="highlight language-ruby"><pre><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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="hll"> <span class="nb">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_path</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">user</span><span class="p">:</span> <span class="p">{</span> <span class="nb">name</span><span class="p">:</span> <span class="nb">name</span><span class="p">,</span>
<span class="ss">email</span><span class="p">:</span> <span class="n">email</span><span class="p">,</span>
<span class="ss">password</span><span class="p">:</span> <span class="s2">""</span><span class="p">,</span>
<span class="ss">password_confirmation</span><span class="p">:</span> <span class="s2">""</span> <span class="p">}</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="o">.</span><span class="n">empty?</span>
<span class="n">assert_redirected_to</span> <span class="vi">@user</span>
<span class="vi">@user</span><span class="o">.</span><span class="n">reload</span>
<span class="n">assert_equal</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="nb">name</span>
<span class="n">assert_equal</span> <span class="vi">@user</span><span class="o">.</span><span class="n">email</span><span class="p">,</span> <span class="n">email</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>有了一个失败测试,现在可以实现友好的转向了。<sup>[<a id="fn-ref-4" href="#fn-4">4</a>]</sup>要转向用户真正想访问的页面,我们要在某个地方存储这个页面的地址,登录后再转向这个页面。我们要通过两个方法来实现这个过程,<code>store_location</code> 和 <code>redirect_back_or</code>,都在会话辅助方法模块中定义,如<a href="#listing-friendly-forwarding-code">代码清单 9.27</a> 所示。</p>
<div id="listing-friendly-forwarding-code" data-type="listing">
<h5><span class="title-label">代码清单 9.27</span>:实现友好的转向</h5>
<div class="source-file">app/helpers/sessions_helper.rb</div>
<div class="highlight language-ruby"><pre><span class="k">module</span> <span class="nn">SessionsHelper</span>
<span class="o">.</span>
<span class="o">.</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="hll"> <span class="n">redirect_to</span><span class="p">(</span><span class="n">session</span><span class="o">[</span><span class="ss">:forwarding_url</span><span class="o">]</span> <span class="o">||</span> <span class="n">default</span><span class="p">)</span>
</span><span class="hll"> <span class="n">session</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="ss">:forwarding_url</span><span class="p">)</span>
</span> <span class="k">end</span>
<span class="c1"># 存储以后需要获取的地址</span>
<span class="k">def</span> <span class="nf">store_location</span>
<span class="hll"> <span class="n">session</span><span class="o">[</span><span class="ss">:forwarding_url</span><span class="o">]</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">url</span> <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">get?</span>
</span> <span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>我们使用 <code>session</code> 存储转向地址,和 <a href="chapter8.html#the-log-in-method">8.2.1 节</a>登入用户的方式类似。<a href="#listing-friendly-forwarding-code">代码清单 9.27</a> 还用到了 <code>request</code> 对象,获取请求页面的地址(<code>request.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-5" href="#fn-5">5</a>]</sup></p>
<p>要使用 <code>store_location</code>,我们要把它加入 <code>logged_in_user</code> 事前过滤器中,如<a href="#listing-add-store-location">代码清单 9.28</a> 所示。</p>
<div id="listing-add-store-location" data-type="listing">
<h5><span class="title-label">代码清单 9.28</span>:把 <code>store_location</code> 添加到 <code>logged_in_user</code> 事前过滤器中</h5>
<div class="source-file">app/controllers/users_controller.rb</div>
<div class="highlight language-ruby"><pre><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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</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="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="o">]</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">def</span> <span class="nf">edit</span>
<span class="k">end</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="o">.</span><span class="n">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span><span class="o">.</span><span class="n">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="o">[</span><span class="ss">:danger</span><span class="o">]</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="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
<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 class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>实现转向操作,要在会话控制器的 <code>create</code> 动作中调用 <code>redirect_back_or</code> 方法,如果存储了之前请求的地址,就重定向这个地址,否则重定向到一个默认的地址,如<a href="#listing-friendly-session-create">代码清单 9.29</a> 所示。<code>redirect_back_or</code> 方法中使用了 <code>||</code> 操作符:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">session</span><span class="o">[</span><span class="ss">:forwarding_url</span><span class="o">]</span> <span class="o">||</span> <span class="n">default</span>
</pre></div>
</div>
<p>如果 <code>session[:forwarding_url]</code> 的值不为 <code>nil</code>,就返回其中存储的值,否则返回默认的地址。注意,<a href="#listing-friendly-forwarding-code">代码清单 9.27</a> 处理得很谨慎,删除了转向地址。如果不删除,后续登录会不断重定向到受保护的页面,用户只能关闭浏览器。(针对这个表现的测试留作<a href="#updating-showing-and-deleting-users-exercises">练习</a>。)还要注意,即便先重定向了,还是会删除会话中的转向地址,因为除非明确使用了 <code>return</code> 或者到了方法的末尾,否则重定向之后的代码仍然会执行。</p>
<div id="listing-friendly-session-create" data-type="listing">
<h5><span class="title-label">代码清单 9.29</span>:加入友好转向后的 <code>create</code> 动作</h5>
<div class="source-file">app/controllers/sessions_controller.rb</div>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">SessionsController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">def</span> <span class="nf">create</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">find_by</span><span class="p">(</span><span class="ss">email</span><span class="p">:</span> <span class="n">params</span><span class="o">[</span><span class="ss">:session</span><span class="o">][</span><span class="ss">:email</span><span class="o">].</span><span class="n">downcase</span><span class="p">)</span>
<span class="k">if</span> <span class="n">user</span> <span class="o">&&</span> <span class="n">user</span><span class="o">.</span><span class="n">authenticate</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:session</span><span class="o">][</span><span class="ss">:password</span><span class="o">]</span><span class="p">)</span>
<span class="n">log_in</span> <span class="n">user</span>
<span class="n">params</span><span class="o">[</span><span class="ss">:session</span><span class="o">][</span><span class="ss">:remember_me</span><span class="o">]</span> <span class="o">==</span> <span class="s1">'1'</span> <span class="p">?</span> <span class="n">remember</span><span class="p">(</span><span class="n">user</span><span class="p">)</span> <span class="p">:</span> <span class="n">forget</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="hll"> <span class="n">redirect_back_or</span> <span class="n">user</span>
</span> <span class="k">else</span>
<span class="n">flash</span><span class="o">.</span><span class="n">now</span><span class="o">[</span><span class="ss">:danger</span><span class="o">]</span> <span class="o">=</span> <span class="s1">'Invalid email/password combination'</span>
<span class="n">render</span> <span class="s1">'new'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>现在,<a href="#listing-friendly-forwarding-test">代码清单 9.26</a> 中针对友好转向的集成测试应该可以通过了。而且,基本的用户认证和页面保护机制也完成了。和之前一样,在继续之前,最好运行测试组件,确认可以通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 9.30</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake <span class="nb">test</span>
</pre></div>
</div>
</section>
</section>
<section data-type="sect1" id="showing-all-users">
<h1><span class="title-label">9.3</span> 列出所有用户</h1>
<p>本节,我们要添加倒数第二个用户控制器动作,<code>index</code>。<code>index</code> 动作不是显示某一个用户,而是显示所有用户。在这个过程中,我们要学习如何在数据库中生成示例用户数据,以及如何分页显示用户列表,让首页显示任意数量的用户。用户列表、分页链接和“Users”(所有用户)导航链接的构思图如<a href="#fig-user-index-mockup">图 9.8</a> 所示。<sup>[<a id="fn-ref-6" href="#fn-6">6</a>]</sup><a href="#deleting-users">9.4 节</a>会添加管理功能,用来删除用户。</p>
<div id="fig-user-index-mockup" class="figure"><img src="images/chapter9/user_index_mockup_bootstrap.png" alt="user index mockup bootstrap" /><div class="figcaption"><span class="title-label">图 9.8</span>:用户列表页面的构思图</div></div>
<section data-type="sect2" id="users-index">
<h2><span class="title-label">9.3.1</span> 用户列表</h2>
<p>创建用户列表之前,我们先要实现一个安全机制。单个用户的资料页面对网站的所有访问者开放,但要限制用户列表页面,只让已登录的用户查看,减少未注册用户能看到的信息量。<sup>[<a id="fn-ref-7" href="#fn-7">7</a>]</sup></p>
<p>为了限制访问 <code>index</code> 动作,我们先编写一个简短的测试,确认应用会正确重定向 <code>index</code> 动作,如<a href="#listing-index-action-redirected-test">代码清单 9.31</a> 所示。</p>
<div id="listing-index-action-redirected-test" data-type="listing">
<h5><span class="title-label">代码清单 9.31</span>:测试 <code>index</code> 动作的重定向 <span class="red">RED</span></h5>
<div class="source-file">test/controllers/users_controller_test.rb</div>
<div class="highlight language-ruby"><pre><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">ActionController</span><span class="o">::</span><span class="no">TestCase</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="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 class="k">end</span>
<span class="hll"> <span class="nb">test</span> <span class="s2">"should redirect index when not logged in"</span> <span class="k">do</span>
</span><span class="hll"> <span class="n">get</span> <span class="ss">:index</span>
</span><span class="hll"> <span class="n">assert_redirected_to</span> <span class="n">login_url</span>
</span><span class="hll"> <span class="k">end</span>
</span> <span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>然后我们要定义 <code>index</code> 动作,并把它加入被 <code>logged_in_user</code> 事前过滤器保护的动作列表中,如<a href="#listing-logged-in-user-index">代码清单 9.32</a> 所示。</p>