-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathchapter10.html
2659 lines (2277 loc) · 252 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.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="account-activation-and-password-reset">
<h1><span class="title-label">第 10 章</span> 账户激活和密码重设</h1>
<p><a href="chapter9.html#updating-showing-and-deleting-users">第 9 章</a>完成了一个基本的用户资源(实现了<a href="chapter7.html#table-restful-users">表 7.1</a> 中的所有 REST 标准动作),以及灵活的认证和权限系统。本章,我们要对这个系统做最后的调整,增加两个联系紧密的功能:账户激活(验证新注册用户的电子邮件地址)和密码重设(帮助忘记密码的用户)。实现这两个功能都要创建新资源,借此机会我们还能再介绍一下控制器、路由和数据库迁移。这两个功能还涉及到一个重要且具挑战的话题——在 Rails 应用中发送电子邮件。而且这两个功能之间需要相互配合,因为重设密码时要向用户的电子邮件地址发送一封包含重设链接的邮件,电子邮件地址是否有效则要在激活账户时验证。<sup>[<a id="fn-ref-1" href="#fn-1">1</a>]</sup></p>
<section data-type="sect1" id="account-activation">
<h1><span class="title-label">10.1</span> 账户激活</h1>
<p>目前,用户注册后立即就能完全控制自己的账户(<a href="chapter7.html#sign-up">第 7 章</a>)。本节,我们要添加一步,激活用户的账户,从而确认用户拥有注册时使用的电子邮件地址。为此,我们要为用户创建激活令牌和摘要,然后给用户发送一封电子邮件,提供包含令牌的链接。用户点击这个链接后,激活这个账户。</p>
<p>我们要采取的实现步骤与注册用户(<a href="chapter8.html#logging-in">8.2 节</a>)和记住用户(<a href="chapter8.html#remember-me">8.4 节</a>)差不多,如下所示:</p>
<ol class="arabic">
<li>
<p>用户一开始处于“未激活”状态;</p>
</li>
<li>
<p>用户注册后,生成一个激活令牌和对应的激活摘要;</p>
</li>
<li>
<p>把激活摘要存储在数据库中,然后给用户发送一封电子邮件,提供一个包含激活令牌和用户电子邮件地址的链接;<sup>[<a id="fn-ref-2" href="#fn-2">2</a>]</sup></p>
</li>
<li>
<p>用户点击这个链接后,使用电子邮件地址查找用户,并且对比令牌和摘要;</p>
</li>
<li>
<p>如果令牌和摘要匹配,就把状态由“未激活”改为“已激活”。</p>
</li>
</ol>
<p>因为与密码和记忆令牌类似,实现账户激活(以及密码重设)功能时可以继续使用前面的很多方法,包括 <code>User.digest</code>、<code>User.new_token</code> 和修改过的 <code>user.authenticated?</code>。这几个功能(包括 <a href="#password-reset">10.2 节</a>要实现的密码重设)之间的对比,如<a href="#table-password-token-digest">表 10.1</a> 所示。我们会在 <a href="#activating-the-account">10.1.3 节</a>定义可用于表中所有情况的通用版 <code>authenticated?</code> 方法。</p>
<table id="table-password-token-digest" class="tableblock frame-all grid-all" style="width: 100%;">
<caption><span class="title-label">表 10.1</span>:登录,记住状态,账户激活和密码重设之间的对比</caption>
<colgroup>
<col style="width: 15%;" />
<col style="width: 20%;" />
<col style="width: 25%;" />
<col style="width: 40%;" />
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">查找方式</th>
<th class="tableblock halign-left valign-top">字符串</th>
<th class="tableblock halign-left valign-top">摘要</th>
<th class="tableblock halign-left valign-top">认证</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>email</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>password</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>password_digest</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>authenticate(password)</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>id</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>remember_token</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>remember_digest</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>authenticated?(:remember, token)</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>email</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>activation_token</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>activation_digest</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>authenticated?(:activation, token)</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>email</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>reset_token</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>reset_digest</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>authenticated?(:reset, token)</code></p></td>
</tr>
</tbody>
</table>
<p>和之前一样,我们要在主题分支中开发新功能。读到 <a href="#email-in-production">10.3 节</a>会发现,账户激活和密码重设需要共用一些电子邮件设置,合并到 <code>master</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 account-activation-password-resets
</pre></div>
</div>
<section data-type="sect2" id="account-activations-resource">
<h2><span class="title-label">10.1.1</span> 资源</h2>
<p>和会话一样(<a href="chapter8.html#sessions">8.1 节</a>),我们要把“账户激活”看做一个资源,不过这个资源不对应模型,相关的数据(激活令牌和激活状态)存储在用户模型中。然而,我们要通过标准的 REST URL 处理账户激活操作。激活链接会改变用户的激活状态,所以我们计划在 <code>edit</code> 动作中处理。<sup>[<a id="fn-ref-3" href="#fn-3">3</a>]</sup>所需的控制器使用下面的命令生成:<sup>[<a id="fn-ref-4" href="#fn-4">4</a>]</sup></p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>rails generate controller AccountActivations --no-test-framework
</pre></div>
</div>
<p>我们需要使用下面的方法生成一个 URL,放在激活邮件中:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">edit_account_activation_url</span><span class="p">(</span><span class="n">activation_token</span><span class="p">,</span> <span class="o">.</span><span class="n">.</span><span class="o">.</span><span class="p">)</span>
</pre></div>
</div>
<p>因此,我们需要为 <code>edit</code> 动作设定一个具名路由——通过<a href="#listing-account-activations-route">代码清单 10.1</a> 中高亮显示的那行 <code>resources</code> 实现。</p>
<div id="listing-account-activations-route" data-type="listing">
<h5><span class="title-label">代码清单 10.1</span>:添加账户激活所需的资源路由</h5>
<div class="source-file">config/routes.rb</div>
<div class="highlight language-ruby"><pre><span class="no">Rails</span><span class="o">.</span><span class="n">application</span><span class="o">.</span><span class="n">routes</span><span class="o">.</span><span class="n">draw</span> <span class="k">do</span>
<span class="n">root</span> <span class="s1">'static_pages#home'</span>
<span class="n">get</span> <span class="s1">'help'</span> <span class="o">=></span> <span class="s1">'static_pages#help'</span>
<span class="n">get</span> <span class="s1">'about'</span> <span class="o">=></span> <span class="s1">'static_pages#about'</span>
<span class="n">get</span> <span class="s1">'contact'</span> <span class="o">=></span> <span class="s1">'static_pages#contact'</span>
<span class="n">get</span> <span class="s1">'signup'</span> <span class="o">=></span> <span class="s1">'users#new'</span>
<span class="n">get</span> <span class="s1">'login'</span> <span class="o">=></span> <span class="s1">'sessions#new'</span>
<span class="n">post</span> <span class="s1">'login'</span> <span class="o">=></span> <span class="s1">'sessions#create'</span>
<span class="n">delete</span> <span class="s1">'logout'</span> <span class="o">=></span> <span class="s1">'sessions#destroy'</span>
<span class="n">resources</span> <span class="ss">:users</span>
<span class="hll"> <span class="n">resources</span> <span class="ss">:account_activations</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="o">]</span>
</span><span class="k">end</span>
</pre></div>
</div>
<p>接下来,我们需要一个唯一的激活令牌,用来激活用户。密码、记忆令牌和密码重设(<a href="#password-reset">10.2 节</a>)需要考虑很多安全隐患,因为如果攻击者获取了这些信息就能完全控制账户。账户激活则不需要这么麻烦,但如果不哈希激活令牌,账户也有一定危险。<sup>[<a id="fn-ref-5" href="#fn-5">5</a>]</sup>所以,参照记住登录状态的做法(<a href="chapter8.html#remember-me">8.4 节</a>),我们会公开令牌,而在数据库中存储哈希摘要。这么做,我们可以使用下面的方式获取激活令牌:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">user</span><span class="o">.</span><span class="n">activation_token</span>
</pre></div>
</div>
<p>使用下面的代码认证用户:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">user</span><span class="o">.</span><span class="n">authenticated?</span><span class="p">(</span><span class="ss">:activation</span><span class="p">,</span> <span class="n">token</span><span class="p">)</span>
</pre></div>
</div>
<p>(不过得先修改<a href="chapter8.html#listing-authenticated-p">代码清单 8.33</a> 中定义的 <code>authenticated?</code> 方法。)我们还要定义一个布尔值属性 <code>activated</code>,使用自动生成的布尔值方法检查用户的激活状态(类似 <a href="chapter9.html#administrative-users">9.4.1 节</a>使用的方法):</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="k">if</span> <span class="n">user</span><span class="o">.</span><span class="n">activated?</span> <span class="o">.</span><span class="n">.</span><span class="o">.</span>
</pre></div>
</div>
<p>最后,我们还要记录激活的日期和时间,虽然本书用不到,但说不定以后需要使用。完整的数据模型如<a href="#fig-user-model-account-activation">图 10.1</a> 所示。</p>
<div id="fig-user-model-account-activation" class="figure"><img src="images/chapter10/user_model_account_activation.png" alt="user model account activation" /><div class="figcaption"><span class="title-label">图 10.1</span>:添加账户激活相关属性后的用户模型</div></div>
<p>下面的命令生成一个迁移,添加这些属性。我们在命令行中指定了要添加的三个属性:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>rails generate migration add_activation_to_users <span class="se">\</span>
> activation_digest:string activated:boolean activated_at:datetime
</pre></div>
</div>
<p>和 <code>admin</code> 属性一样(<a href="chapter9.html#listing-admin-migration">代码清单 9.50</a>),我们要把 <code>activated</code> 属性的默认值设为 <code>false</code>,如<a href="#listing-add-activation-to-users-migration">代码清单 10.2</a> 所示。</p>
<div id="listing-add-activation-to-users-migration" data-type="listing">
<h5><span class="title-label">代码清单 10.2</span>:添加账户激活所需属性的迁移</h5>
<div class="source-file">db/migrate/[timestamp]_add_activation_to_users.rb</div>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">AddActivationToUsers</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">add_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:activation_digest</span><span class="p">,</span> <span class="ss">:string</span>
<span class="hll"> <span class="n">add_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:activated</span><span class="p">,</span> <span class="ss">:boolean</span><span class="p">,</span> <span class="ss">default</span><span class="p">:</span> <span class="kp">false</span>
</span> <span class="n">add_column</span> <span class="ss">:users</span><span class="p">,</span> <span class="ss">:activated_at</span><span class="p">,</span> <span class="ss">:datetime</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>然后像之前一样,执行迁移:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake db:migrate
</pre></div>
</div>
<p>因为每个新注册的用户都得激活,所以我们应该在创建用户对象之前为用户分配激活令牌和摘要。类似的操作在 <a href="chapter6.html#uniqueness-validation">6.2.5 节</a>见过,那时我们要在用户存入数据库之前把电子邮件地址转换成小写形式。我们使用的是 <code>before_save</code> 回调和 <code>downcase</code> 方法(<a href="chapter6.html#listing-email-downcase">代码清单 6.31</a>)。<code>before_save</code> 回调在保存对象之前,包括创建对象和更新对象,自动调用。不过现在我们只想在创建用户之前调用回调,创建激活摘要。为此,我们要使用 <code>before_create</code> 回调,按照下面的方式定义:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">before_create</span> <span class="ss">:create_activation_digest</span>
</pre></div>
</div>
<p>这种写法叫“方法引用”,Rails 会寻找一个名为 <code>create_activation_digest</code> 的方法,在创建用户之前调用。(在<a href="chapter6.html#listing-email-downcase">代码清单 6.31</a> 中,我们直接把一个块传给 <code>before_save</code>。不过方法引用是推荐的做法。)<code>create_activation_digest</code> 方法只会在用户模型内使用,没必要公开。如 <a href="chapter7.html#strong-parameters">7.3.2 节</a>所示,在 Ruby 中可以使用 <code>private</code> 实现这个需求:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="kp">private</span>
<span class="k">def</span> <span class="nf">create_activation_digest</span>
<span class="c1"># 创建令牌和摘要</span>
<span class="k">end</span>
</pre></div>
</div>
<p>在一个类中,<code>private</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">first</span><span class="o">.</span><span class="n">create_activation_digest</span>
<span class="go">NoMethodError: private method `create_activation_digest' called for #<User></span>
</pre></div>
</div>
<p>这个 <code>before_create</code> 回调的作用是为用户分配令牌和对应的摘要,实现的方法如下所示:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="nb">self</span><span class="o">.</span><span class="n">activation_token</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">new_token</span>
<span class="nb">self</span><span class="o">.</span><span class="n">activation_digest</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">digest</span><span class="p">(</span><span class="n">activation_token</span><span class="p">)</span>
</pre></div>
</div>
<p>这里用到了实现“记住我”功能时用来生成令牌和摘要的方法。我们可以把这两行代码和<a href="chapter8.html#listing-user-model-remember">代码清单 8.32</a> 中的 <code>remember</code> 方法比较一下:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="c1"># 为了持久会话,在数据库中记住用户</span>
<span class="k">def</span> <span class="nf">remember</span>
<span class="nb">self</span><span class="o">.</span><span class="n">remember_token</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">new_token</span>
<span class="n">update_attribute</span><span class="p">(</span><span class="ss">:remember_digest</span><span class="p">,</span> <span class="no">User</span><span class="o">.</span><span class="n">digest</span><span class="p">(</span><span class="n">remember_token</span><span class="p">))</span>
<span class="k">end</span>
</pre></div>
</div>
<p>二者之间的主要区别是,<code>remember</code> 方法中使用的是 <code>update_attribute</code>。因为,创建记忆令牌和摘要时,用户已经存在于数据库中了,而 <code>before_create</code> 回调在创建用户之前执行。有了这个回调,使用 <code>User.new</code> 新建用户后(例如用户注册后,参见<a href="chapter7.html#listing-create-action-strong-parameters">代码清单 7.17</a>),会自动赋值 <code>activation_token</code> 和 <code>activation_digest</code> 属性,而且因为 <code>activation_digest</code> 对应数据库中的一个列(<a href="#fig-user-model-account-activation">图 10.1</a>),所以保存用户时会自动把属性的值存入数据库。</p>
<p>综上所述,用户模型如<a href="#listing-user-model-activation-code">代码清单 10.3</a> 所示。因为激活令牌是虚拟属性,所以我们又添加了一个 <code>attr_accessor</code>。注意,我们还把电子邮件地址转换成小写的回调改成了方法引用形式。</p>
<div id="listing-user-model-activation-code" data-type="listing">
<h5><span class="title-label">代码清单 10.3</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="hll"> <span class="kp">attr_accessor</span> <span class="ss">:remember_token</span><span class="p">,</span> <span class="ss">:activation_token</span>
</span><span class="hll"> <span class="n">before_save</span> <span class="ss">:downcase_email</span>
</span><span class="hll"> <span class="n">before_create</span> <span class="ss">:create_activation_digest</span>
</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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="kp">private</span>
<span class="c1"># 把电子邮件地址转换成小写</span>
<span class="k">def</span> <span class="nf">downcase_email</span>
<span class="hll"> <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> <span class="k">end</span>
<span class="c1"># 创建并赋值激活令牌和摘要</span>
<span class="k">def</span> <span class="nf">create_activation_digest</span>
<span class="hll"> <span class="nb">self</span><span class="o">.</span><span class="n">activation_token</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">new_token</span>
</span><span class="hll"> <span class="nb">self</span><span class="o">.</span><span class="n">activation_digest</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">digest</span><span class="p">(</span><span class="n">activation_token</span><span class="p">)</span>
</span> <span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>在继续之前,我们还要修改种子数据,把示例用户和测试用户设为已激活,如<a href="#listing-seed-users-activated">代码清单 10.4</a> 和<a href="#listing-fixture-users-activated">代码清单 10.5</a> 所示。(<code>Time.zone.now</code> 是 Rails 提供的辅助方法,基于服务器使用的时区,返回当前时间戳。)</p>
<div id="listing-seed-users-activated" data-type="listing">
<h5><span class="title-label">代码清单 10.4</span>:激活种子数据中的用户</h5>
<div class="source-file">db/seeds.rb</div>
<div class="highlight language-yaml"><pre><span class="l-Scalar-Plain">User.create!(name</span><span class="p-Indicator">:</span> <span class="s">"Example</span><span class="nv"> </span><span class="s">User"</span><span class="err">,</span>
<span class="l-Scalar-Plain">email</span><span class="p-Indicator">:</span> <span class="s">"[email protected]"</span><span class="err">,</span>
<span class="l-Scalar-Plain">password</span><span class="p-Indicator">:</span> <span class="s">"foobar"</span><span class="err">,</span>
<span class="l-Scalar-Plain">password_confirmation</span><span class="p-Indicator">:</span> <span class="s">"foobar"</span><span class="err">,</span>
<span class="l-Scalar-Plain">admin</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true,</span>
<span class="hll"> <span class="l-Scalar-Plain">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true,</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Time.zone.now)</span>
</span>
<span class="l-Scalar-Plain">99.times do |n|</span>
<span class="l-Scalar-Plain">name = Faker::Name.name</span>
<span class="l-Scalar-Plain">email = "example-#{n+1}@railstutorial.org"</span>
<span class="l-Scalar-Plain">password = "password"</span>
<span class="l-Scalar-Plain">User.create!(name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">name,</span>
<span class="l-Scalar-Plain">email</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">email,</span>
<span class="l-Scalar-Plain">password</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">password,</span>
<span class="l-Scalar-Plain">password_confirmation</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">password,</span>
<span class="hll"> <span class="l-Scalar-Plain">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true,</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Time.zone.now)</span>
</span><span class="l-Scalar-Plain">end</span>
</pre></div>
</div>
<div id="listing-fixture-users-activated" data-type="listing">
<h5><span class="title-label">代码清单 10.5</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="l-Scalar-Plain">admin</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
<span class="hll"> <span class="l-Scalar-Plain">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= Time.zone.now %></span>
</span>
<span class="l-Scalar-Plain">archer</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Sterling Archer</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">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= Time.zone.now %></span>
</span>
<span class="l-Scalar-Plain">lana</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Lana Kane</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">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= Time.zone.now %></span>
</span>
<span class="l-Scalar-Plain">malory</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Malory Archer</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">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= Time.zone.now %></span>
</span>
<span class="l-Scalar-Plain"><% 30.times do |n| %></span>
<span class="l-Scalar-Plain">user_<%= n %></span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">name</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= "User</span> <span class="c1">#{n}" %></span>
<span class="l-Scalar-Plain">email</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= "user-#{n}@example.com" %></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">activated</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</span><span class="hll"> <span class="l-Scalar-Plain">activated_at</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain"><%= Time.zone.now %></span>
</span><span class="l-Scalar-Plain"><% end %></span>
</pre></div>
</div>
<p>为了应用<a href="#listing-seed-users-activated">代码清单 10.4</a> 中的改动,我们要还原数据库,然后像之前一样写入数据:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>bundle <span class="nb">exec </span>rake db:migrate:reset
<span class="nv">$ </span>bundle <span class="nb">exec </span>rake db:seed
</pre></div>
</div>
</section>
<section data-type="sect2" id="account-activation-mailer-method">
<h2><span class="title-label">10.1.2</span> 邮件程序</h2>
<p>写好模型后,我们要编写发送账户激活邮件的代码了。我们要使用 Action Mailer 库创建一个邮件程序,在用户控制器的 <code>create</code> 动作中发送一封包含激活链接的邮件。邮件程序的结构和控制器动作差不多,邮件模板使用视图定义。这一节的任务是创建邮件程序,以及编写视图,写入激活账户所需的激活令牌和电子邮件地址。</p>
<p>与模型和控制器一样,我们可以使用 <code>rails generate</code> 生成邮件程序:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><span class="nv">$ </span>rails generate mailer UserMailer account_activation password_reset
</pre></div>
</div>
<p>我们使用这个命令生成了所需的 <code>account_activation</code> 方法,以及 <a href="#password-reset">10.2 节</a>要使用的 <code>password_reset</code> 方法。</p>
<p>生成邮件程序时,Rails 还为每个邮件程序生成了两个视图模板,一个用于纯文本邮件,一个用于 HTML 邮件。账户激活邮件程序的两个视图如<a href="#listing-generated-account-activation-view-text">代码清单 10.6</a> 和<a href="#listing-generated-account-activation-view-html">代码清单 10.7</a> 所示。</p>
<div id="listing-generated-account-activation-view-text" data-type="listing">
<h5><span class="title-label">代码清单 10.6</span>:生成的账户激活邮件视图,纯文本格式</h5>
<div class="source-file">app/views/user_mailer/account_activation.text.erb</div>
<div class="highlight language-erb"><pre><span class="x">UserMailer#account_activation</span>
<span class="cp"><%=</span> <span class="vi">@greeting</span> <span class="cp">%></span><span class="x">, find me in app/views/user_mailer/account_activation.text.erb</span>
</pre></div>
</div>
<div id="listing-generated-account-activation-view-html" data-type="listing">
<h5><span class="title-label">代码清单 10.7</span>:生成的账户激活邮件视图,HTML 格式</h5>
<div class="source-file">app/views/user_mailer/account_activation.html.erb</div>
<div class="highlight language-erb"><pre><span class="x"><h1>UserMailer#account_activation</h1></span>
<span class="x"><p></span>
<span class="x"> </span><span class="cp"><%=</span> <span class="vi">@greeting</span> <span class="cp">%></span><span class="x">, find me in app/views/user_mailer/account_activation.html.erb</span>
<span class="x"></p></span>
</pre></div>
</div>
<p>我们看一下生成的邮件程序,了解它是如何工作的,如<a href="#listing-generated-application-mailer">代码清单 10.8</a> 和<a href="#listing-generated-user-mailer">代码清单 10.9</a>所示。代码<a href="#listing-generated-application-mailer">代码清单 10.8</a> 设置了一个默认的发件人地址(<code>from</code>),整个应用中的全部邮件程序都会使用这个地址。(这个代码清单还设置了各种邮件格式使用的布局。本书不会讨论邮件的布局,生成的 HTML 和纯文本格式邮件布局在 <code>app/views/layouts</code> 文件夹中。)<a href="#listing-generated-user-mailer">代码清单 10.9</a> 中的每个方法中都设置了收件人地址。在生成的代码中还有一个实例变量 <code>@greeting</code>,这个变量可在邮件程序的视图中使用,就像控制器中的实例变量可以在普通的视图中使用一样。</p>
<div id="listing-generated-application-mailer" data-type="listing">
<h5><span class="title-label">代码清单 10.8</span>:生成的 <code>ApplicationMailer</code></h5>
<div class="source-file">app/mailers/application_mailer.rb</div>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">ApplicationMailer</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span>
<span class="n">default</span> <span class="ss">from</span><span class="p">:</span> <span class="s2">"[email protected]"</span>
<span class="n">layout</span> <span class="s1">'mailer'</span>
<span class="k">end</span>
</pre></div>
</div>
<div id="listing-generated-user-mailer" data-type="listing">
<h5><span class="title-label">代码清单 10.9</span>:生成的 <code>UserMailer</code></h5>
<div class="source-file">app/mailers/user_mailer.rb</div>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">UserMailer</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span>
<span class="c1"># Subject can be set in your I18n file at config/locales/en.yml</span>
<span class="c1"># with the following lookup:</span>
<span class="c1">#</span>
<span class="c1"># en.user_mailer.account_activation.subject</span>
<span class="c1">#</span>
<span class="k">def</span> <span class="nf">account_activation</span>
<span class="hll"> <span class="vi">@greeting</span> <span class="o">=</span> <span class="s2">"Hi"</span>
</span>
<span class="hll"> <span class="n">mail</span> <span class="ss">to</span><span class="p">:</span> <span class="s2">"[email protected]"</span>
</span> <span class="k">end</span>
<span class="c1"># Subject can be set in your I18n file at config/locales/en.yml</span>
<span class="c1"># with the following lookup:</span>
<span class="c1">#</span>
<span class="c1"># en.user_mailer.password_reset.subject</span>
<span class="c1">#</span>
<span class="k">def</span> <span class="nf">password_reset</span>
<span class="hll"> <span class="vi">@greeting</span> <span class="o">=</span> <span class="s2">"Hi"</span>
</span>
<span class="hll"> <span class="n">mail</span> <span class="ss">to</span><span class="p">:</span> <span class="s2">"[email protected]"</span>
</span> <span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>为了发送激活邮件,我们首先要修改生成的模板,如<a href="#listing-application-mailer">代码清单 10.10</a> 所示。然后要创建一个实例变量,其值是用户对象,以便在视图中使用,然后把邮件发给 <code>user.email</code>。如<a href="#listing-mail-account-activation">代码清单 10.11</a> 所示,<code>mail</code> 方法还可以接受 <code>subject</code> 参数,指定邮件的主题。</p>
<div id="listing-application-mailer" data-type="listing">
<h5><span class="title-label">代码清单 10.10</span>:在 <code>ApplicationMailer</code> 中设定默认的发件人地址</h5>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">ApplicationMailer</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span>
<span class="n">default</span> <span class="ss">from</span><span class="p">:</span> <span class="s2">"[email protected]"</span>
<span class="n">layout</span> <span class="s1">'mailer'</span>
<span class="k">end</span>
</pre></div>
</div>
<div id="listing-mail-account-activation" data-type="listing">
<h5><span class="title-label">代码清单 10.11</span>:发送账户激活链接</h5>
<div class="source-file">app/mailers/user_mailer.rb</div>
<div class="highlight language-ruby"><pre><span class="k">class</span> <span class="nc">UserMailer</span> <span class="o"><</span> <span class="no">ApplicationMailer</span>
<span class="hll"> <span class="k">def</span> <span class="nf">account_activation</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
</span><span class="hll"> <span class="vi">@user</span> <span class="o">=</span> <span class="n">user</span>
</span><span class="hll"> <span class="n">mail</span> <span class="ss">to</span><span class="p">:</span> <span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="p">,</span> <span class="ss">subject</span><span class="p">:</span> <span class="s2">"Account activation"</span>
</span><span class="hll"> <span class="k">end</span>
</span>
<span class="k">def</span> <span class="nf">password_reset</span>
<span class="vi">@greeting</span> <span class="o">=</span> <span class="s2">"Hi"</span>
<span class="n">mail</span> <span class="ss">to</span><span class="p">:</span> <span class="s2">"[email protected]"</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>和普通的视图一样,在邮件程序的视图中也可以使用嵌入式 Ruby。在邮件中我们要添加一个针对用户的欢迎消息,以及一个激活链接。我们计划使用电子邮件地址查找用户,然后使用激活令牌认证用户,所以链接中要包含电子邮件地址和令牌。因为我们把“账户激活”视作一个资源,所以可以把令牌作为参数传给<a href="#listing-account-activations-route">代码清单 10.1</a> 中定义的具名路由:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">edit_account_activation_url</span><span class="p">(</span><span class="vi">@user</span><span class="o">.</span><span class="n">activation_token</span><span class="p">,</span> <span class="o">.</span><span class="n">.</span><span class="o">.</span><span class="p">)</span>
</pre></div>
</div>
<p>我们知道,<code>edit_user_url(user)</code> 生成的地址是下面这种形式:</p>
<div data-type="listing">
<div class="highlight language-text"><pre>http://www.example.com/users/1/edit
</pre></div>
</div>
<p>那么,账户激活的链接应该是这种形式:</p>
<div data-type="listing">
<div class="highlight language-text"><pre>http://www.example.com/account_activations/q5lt38hQDc_959PVoo6b7A/edit
</pre></div>
</div>
<p>其中,<code>q5lt38hQDc_959PVoo6b7A</code> 是使用 <code>new_token</code> 方法(<a href="chapter8.html#listing-token-method">代码清单 8.31</a>)生成的 base64 字符串,可安全地在 URL 中使用。这个值的作用和 /users/1/edit 中的用户 ID 一样,在 <code>AccountActivationsController</code> 的 <code>edit</code> 动作中可以通过 <code>params[:id]</code> 获取。</p>
<p>为了包含电子邮件地址,我们要使用“查询参数”(query parameter)。查询参数放在 URL 中的问号后面,使用键值对形式指定:<sup>[<a id="fn-ref-6" href="#fn-6">6</a>]</sup></p>
<div data-type="listing">
<div class="highlight language-text"><pre>account_activations/q5lt38hQDc_959PVoo6b7A/edit?email=foo%40example.com
</pre></div>
</div>
<p>注意,电子邮件地址中的“@”被替换成了 <code>%40</code>,也就是被转义了,这样,URL 才是有效的。在 Rails 中设定查询参数的方法是,把一个哈希传给具名路由:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">edit_account_activation_url</span><span class="p">(</span><span class="vi">@user</span><span class="o">.</span><span class="n">activation_token</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>params[:email]</code> 可以获取电子邮件地址。</p>
<p>定义好实例变量 <code>@user</code> 之后(<a href="#listing-mail-account-activation">代码清单 10.11</a>),我们可以使用 <code>edit</code> 动作的具名路由和嵌入式 Ruby 创建所需的链接了,如<a href="#listing-account-activation-view-text">代码清单 10.12</a> 和<a href="#listing-account-activation-view-html">代码清单 10.13</a> 所示。注意,在<a href="#listing-account-activation-view-html">代码清单 10.13</a> 中,我们使用 <code>link_to</code> 方法创建有效的链接。</p>
<div id="listing-account-activation-view-text" data-type="listing">
<h5><span class="title-label">代码清单 10.12</span>:账户激活邮件的纯文本视图</h5>
<div class="source-file">app/views/user_mailer/account_activation.text.erb</div>
<div class="highlight language-erb"><pre><span class="x">Hi </span><span class="cp"><%=</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span> <span class="cp">%></span><span class="x">,</span>
<span class="x">Welcome to the Sample App! Click on the link below to activate your account:</span>
<span class="cp"><%=</span> <span class="n">edit_account_activation_url</span><span class="p">(</span><span class="vi">@user</span><span class="o">.</span><span class="n">activation_token</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="cp">%></span><span class="x"></span>
</pre></div>
</div>
<div id="listing-account-activation-view-html" data-type="listing">
<h5><span class="title-label">代码清单 10.13</span>:账户激活邮件的 HTML 视图</h5>
<div class="source-file">app/views/user_mailer/account_activation.html.erb</div>
<div class="highlight language-erb"><pre><span class="x"><h1>Sample App</h1></span>
<span class="x"><p>Hi </span><span class="cp"><%=</span> <span class="vi">@user</span><span class="o">.</span><span class="n">name</span> <span class="cp">%></span><span class="x">,</p></span>
<span class="x"><p></span>
<span class="x">Welcome to the Sample App! Click on the link below to activate your account:</span>
<span class="x"></p></span>
<span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Activate"</span><span class="p">,</span> <span class="n">edit_account_activation_url</span><span class="p">(</span><span class="vi">@user</span><span class="o">.</span><span class="n">activation_token</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="cp">%></span><span class="x"></span>
</pre></div>
</div>
<p>若想查看这两个邮件视图的效果,我们可以使用邮件预览功能。Rails 提供了一些特殊的 URL,用来预览邮件。首先,我们要在应用的开发环境中添加一些设置,如<a href="#listing-development-email-settings">代码清单 10.14</a> 所示。</p>
<div id="listing-development-email-settings" data-type="listing">
<h5><span class="title-label">代码清单 10.14</span>:开发环境中的邮件设置</h5>
<div class="source-file">config/environments/development.rb</div>
<div class="highlight language-ruby"><pre><span class="no">Rails</span><span class="o">.</span><span class="n">application</span><span class="o">.</span><span class="n">configure</span> <span class="k">do</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="n">config</span><span class="o">.</span><span class="n">action_mailer</span><span class="o">.</span><span class="n">raise_delivery_errors</span> <span class="o">=</span> <span class="kp">true</span>
<span class="n">config</span><span class="o">.</span><span class="n">action_mailer</span><span class="o">.</span><span class="n">delivery_method</span> <span class="o">=</span> <span class="ss">:test</span>
<span class="n">host</span> <span class="o">=</span> <span class="s1">'example.com'</span>
<span class="n">config</span><span class="o">.</span><span class="n">action_mailer</span><span class="o">.</span><span class="n">default_url_options</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">host</span><span class="p">:</span> <span class="n">host</span> <span class="p">}</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-development-email-settings">代码清单 10.14</a> 中设置的主机地址是 <code>'example.com'</code>,你应该使用你的开发环境的主机地址。例如,在我的系统中,可以使用下面的地址(包括云端 IDE 和本地服务器):</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">host</span> <span class="o">=</span> <span class="s1">'rails-tutorial-c9-mhartl.c9.io'</span> <span class="c1"># 云端 IDE</span>
<span class="n">host</span> <span class="o">=</span> <span class="s1">'localhost:3000'</span> <span class="c1"># 本地主机</span>
</pre></div>
</div>
<p>然后重启开发服务器,让<a href="#listing-development-email-settings">代码清单 10.14</a> 中的设置生效。接下来,我们要修改邮件程序的预览文件。生成邮件程序时已经自动生成了这个文件,如<a href="#listing-generated-user-mailer-previews">代码清单 10.15</a> 所示。</p>
<div id="listing-generated-user-mailer-previews" data-type="listing">
<h5><span class="title-label">代码清单 10.15</span>:生成的邮件预览程序</h5>
<div class="source-file">test/mailers/previews/user_mailer_preview.rb</div>
<div class="highlight language-ruby"><pre><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/user_mailer</span>
<span class="k">class</span> <span class="nc">UserMailerPreview</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
<span class="c1"># Preview this email at</span>
<span class="c1"># http://localhost:3000/rails/mailers/user_mailer/account_activation</span>
<span class="k">def</span> <span class="nf">account_activation</span>
<span class="no">UserMailer</span><span class="o">.</span><span class="n">account_activation</span>
<span class="k">end</span>
<span class="c1"># Preview this email at</span>
<span class="c1"># http://localhost:3000/rails/mailers/user_mailer/password_reset</span>
<span class="k">def</span> <span class="nf">password_reset</span>
<span class="no">UserMailer</span><span class="o">.</span><span class="n">password_reset</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>因为<a href="#listing-mail-account-activation">代码清单 10.11</a> 中定义的 <code>account_activation</code> 方法需要一个有效的用户作为参数,所以<a href="#listing-generated-user-mailer-previews">代码清单 10.15</a> 中的代码现在还不能使用。为了解决这个问题,我们要定义 <code>user</code> 变量,把开发数据库中的第一个用户赋值给它,然后作为参数传给 <code>UserMailer.account_activation</code>,如<a href="#listing-account-activation-preview">代码清单 10.16</a> 所示。注意,在这段代码中,我们还给 <code>user.activation_token</code> 赋了值,因为<a href="#listing-account-activation-view-text">代码清单 10.12</a> 和<a href="#listing-account-activation-view-html">代码清单 10.13</a> 中的模板要使用账户激活令牌。(<code>activation_token</code> 是虚拟属性,所以数据库中的用户并没有激活令牌。)</p>
<div id="listing-account-activation-preview" data-type="listing">
<h5><span class="title-label">代码清单 10.16</span>:预览账户激活邮件所需的方法</h5>
<div class="source-file">test/mailers/previews/user_mailer_preview.rb</div>
<div class="highlight language-ruby"><pre><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/user_mailer</span>
<span class="k">class</span> <span class="nc">UserMailerPreview</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
<span class="c1"># Preview this email at</span>
<span class="c1"># http://localhost:3000/rails/mailers/user_mailer/account_activation</span>
<span class="k">def</span> <span class="nf">account_activation</span>
<span class="hll"> <span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">first</span>
</span><span class="hll"> <span class="n">user</span><span class="o">.</span><span class="n">activation_token</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">new_token</span>
</span><span class="hll"> <span class="no">UserMailer</span><span class="o">.</span><span class="n">account_activation</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
</span> <span class="k">end</span>
<span class="c1"># Preview this email at</span>
<span class="c1"># http://localhost:3000/rails/mailers/user_mailer/password_reset</span>
<span class="k">def</span> <span class="nf">password_reset</span>
<span class="no">UserMailer</span><span class="o">.</span><span class="n">password_reset</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>这样修改之后,我们就可以访问注释中提示的 URL 预览账户激活邮件了。(如果使用云端 IDE,要把 <code>localhost:3000</code> 换成相应的 URL。)HTML 和纯文本邮件分别如<a href="#fig-account-activation-html-preview">图 10.2</a> 和<a href="#fig-account-activation-text-preview">图 10.3</a> 所示。</p>
<div id="fig-account-activation-html-preview" class="figure"><img src="images/chapter10/account_activation_html_preview.png" alt="account activation html preview" /><div class="figcaption"><span class="title-label">图 10.2</span>:预览 HTML 格式的账户激活邮件</div></div>
<div id="fig-account-activation-text-preview" class="figure"><img src="images/chapter10/account_activation_text_preview.png" alt="account activation text preview" /><div class="figcaption"><span class="title-label">图 10.3</span>:预览纯文本格式的账户激活邮件</div></div>
<p>最后,我们要编写一些测试,再次确认邮件的内容。这并不难,因为 Rails 生成了一些有用的测试示例,如<a href="#listing-generated-user-mailer-test">代码清单 10.17</a> 所示。</p>
<div id="listing-generated-user-mailer-test" data-type="listing">
<h5><span class="title-label">代码清单 10.17</span>:Rails 生成的 <code>UserMailer</code> 测试</h5>
<div class="source-file">test/mailers/user_mailer_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">UserMailerTest</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">TestCase</span>
<span class="nb">test</span> <span class="s2">"account_activation"</span> <span class="k">do</span>
<span class="n">mail</span> <span class="o">=</span> <span class="no">UserMailer</span><span class="o">.</span><span class="n">account_activation</span>
<span class="n">assert_equal</span> <span class="s2">"Account activation"</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">subject</span>
<span class="n">assert_equal</span> <span class="o">[</span><span class="s2">"[email protected]"</span><span class="o">]</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">to</span>
<span class="n">assert_equal</span> <span class="o">[</span><span class="s2">"[email protected]"</span><span class="o">]</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">from</span>
<span class="n">assert_match</span> <span class="s2">"Hi"</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">body</span><span class="o">.</span><span class="n">encoded</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"password_reset"</span> <span class="k">do</span>
<span class="n">mail</span> <span class="o">=</span> <span class="no">UserMailer</span><span class="o">.</span><span class="n">password_reset</span>
<span class="n">assert_equal</span> <span class="s2">"Password reset"</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">subject</span>
<span class="n">assert_equal</span> <span class="o">[</span><span class="s2">"[email protected]"</span><span class="o">]</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">to</span>
<span class="n">assert_equal</span> <span class="o">[</span><span class="s2">"[email protected]"</span><span class="o">]</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">from</span>
<span class="n">assert_match</span> <span class="s2">"Hi"</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">body</span><span class="o">.</span><span class="n">encoded</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p><a href="#listing-generated-user-mailer-test">代码清单 10.17</a> 中使用了强大的 <code>assert_match</code> 方法。这个方法既可以匹配字符串,也可以匹配正则表达式:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">assert_match</span> <span class="s1">'foo'</span><span class="p">,</span> <span class="s1">'foobar'</span> <span class="c1"># true</span>
<span class="n">assert_match</span> <span class="s1">'baz'</span><span class="p">,</span> <span class="s1">'foobar'</span> <span class="c1"># false</span>
<span class="n">assert_match</span> <span class="sr">/\w+/</span><span class="p">,</span> <span class="s1">'foobar'</span> <span class="c1"># true</span>
<span class="n">assert_match</span> <span class="sr">/\w+/</span><span class="p">,</span> <span class="s1">'$#!*+@'</span> <span class="c1"># false</span>
</pre></div>
</div>
<p><a href="#listing-real-account-activation-test">代码清单 10.18</a> 使用 <code>assert_match</code> 检查邮件正文中是否有用户的名字、激活令牌和转义后的电子邮件地址。注意,转义用户电子邮件地址使用的方法是 <code>CGI::escape(user.email)</code>。<sup>[<a id="fn-ref-7" href="#fn-7">7</a>]</sup>(其实还有第三种方法,<code>ERB::Util</code> 中的 <a href="http://apidock.com/ruby/ERB/Util/url_encode"><code>url_encode</code> 方法</a>有同样的效果。)</p>
<div id="listing-real-account-activation-test" data-type="listing">
<h5><span class="title-label">代码清单 10.18</span>:测试现在这个邮件程序 <span class="red">RED</span></h5>
<div class="source-file">test/mailers/user_mailer_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">UserMailerTest</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">TestCase</span>
<span class="nb">test</span> <span class="s2">"account_activation"</span> <span class="k">do</span>
<span class="n">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="n">user</span><span class="o">.</span><span class="n">activation_token</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">new_token</span>
<span class="n">mail</span> <span class="o">=</span> <span class="no">UserMailer</span><span class="o">.</span><span class="n">account_activation</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="n">assert_equal</span> <span class="s2">"Account activation"</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">subject</span>
<span class="n">assert_equal</span> <span class="o">[</span><span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="o">]</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">to</span>
<span class="n">assert_equal</span> <span class="o">[</span><span class="s2">"[email protected]"</span><span class="o">]</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">from</span>
<span class="n">assert_match</span> <span class="n">user</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">body</span><span class="o">.</span><span class="n">encoded</span>
<span class="n">assert_match</span> <span class="n">user</span><span class="o">.</span><span class="n">activation_token</span><span class="p">,</span> <span class="n">mail</span><span class="o">.</span><span class="n">body</span><span class="o">.</span><span class="n">encoded</span>
<span class="n">assert_match</span> <span class="no">CGI</span><span class="o">::</span><span class="n">escape</span><span class="p">(</span><span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="p">),</span> <span class="n">mail</span><span class="o">.</span><span class="n">body</span><span class="o">.</span><span class="n">encoded</span>
<span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>注意,我们在<a href="#listing-real-account-activation-test">代码清单 10.18</a> 中为用户固件指定了激活令牌,因为固件中没有虚拟属性。</p>
<p>为了让这个测试通过,我们要修改测试环境的配置,设定正确的主机地址,如<a href="#listing-test-domain-host">代码清单 10.19</a> 所示。</p>
<div id="listing-test-domain-host" data-type="listing">
<h5><span class="title-label">代码清单 10.19</span>:设定测试环境的主机地址</h5>
<div class="source-file">config/environments/test.rb</div>
<div class="highlight language-ruby"><pre><span class="no">Rails</span><span class="o">.</span><span class="n">application</span><span class="o">.</span><span class="n">configure</span> <span class="k">do</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="n">config</span><span class="o">.</span><span class="n">action_mailer</span><span class="o">.</span><span class="n">delivery_method</span> <span class="o">=</span> <span class="ss">:test</span>
<span class="hll"> <span class="n">config</span><span class="o">.</span><span class="n">action_mailer</span><span class="o">.</span><span class="n">default_url_options</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">host</span><span class="p">:</span> <span class="s1">'example.com'</span> <span class="p">}</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">代码清单 10.20</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>:mailers
</pre></div>
</div>
<p>若要在我们的应用中使用这个邮件程序,只需在处理用户注册的 <code>create</code> 动作中添加几行代码,如<a href="#listing-user-signup-with-account-activation">代码清单 10.21</a> 所示。注意,<a href="#listing-user-signup-with-account-activation">代码清单 10.21</a> 修改了注册后的重定向地址。之前,我们把用户重定向到资料页面(<a href="chapter7.html#successful-signups">7.4 节</a>),可是现在需要先激活,再转向这个页面就不合理了,所以把重定向地址改成了根地址。</p>
<div id="listing-user-signup-with-account-activation" data-type="listing">
<h5><span class="title-label">代码清单 10.21</span>:在注册过程中添加账户激活 <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">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="hll"> <span class="no">UserMailer</span><span class="o">.</span><span class="n">account_activation</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span><span class="o">.</span><span class="n">deliver_now</span>
</span><span class="hll"> <span class="n">flash</span><span class="o">[</span><span class="ss">:info</span><span class="o">]</span> <span class="o">=</span> <span class="s2">"Please check your email to activate your account."</span>
</span><span class="hll"> <span class="n">redirect_to</span> <span class="n">root_url</span>
</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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="k">end</span>
</pre></div>
</div>
<p>因为现在重定向到根地址而不是资料页面,而且不会像之前那样自动登入用户,所以测试组件无法通过,不过应用能按照我们设计的方式运行。我们暂时把导致失败的测试注释掉,如<a href="#listing-comment-out-failing-tests">代码清单 10.22</a> 所示。我们会在 <a href="#activation-test-and-refactoring">10.1.4 节</a>去掉注释,并且为账户激活编写能通过的测试。</p>
<div id="listing-comment-out-failing-tests" data-type="listing">
<h5><span class="title-label">代码清单 10.22</span>:临时注释掉失败的测试 <span class="green">GREEN</span></h5>
<div class="source-file">test/integration/users_signup_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">UsersSignupTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="nb">test</span> <span class="s2">"invalid signup information"</span> <span class="k">do</span>
<span class="n">get</span> <span class="n">signup_path</span>
<span class="n">assert_no_difference</span> <span class="s1">'User.count'</span> <span class="k">do</span>
<span class="n">post</span> <span class="n">users_path</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="s2">""</span><span class="p">,</span>
<span class="ss">email</span><span class="p">:</span> <span class="s2">"user@invalid"</span><span class="p">,</span>
<span class="ss">password</span><span class="p">:</span> <span class="s2">"foo"</span><span class="p">,</span>
<span class="ss">password_confirmation</span><span class="p">:</span> <span class="s2">"bar"</span> <span class="p">}</span>
<span class="k">end</span>
<span class="n">assert_template</span> <span class="s1">'users/new'</span>
<span class="n">assert_select</span> <span class="s1">'div#error_explanation'</span>
<span class="n">assert_select</span> <span class="s1">'div.field_with_errors'</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"valid signup information"</span> <span class="k">do</span>
<span class="n">get</span> <span class="n">signup_path</span>
<span class="n">assert_difference</span> <span class="s1">'User.count'</span><span class="p">,</span> <span class="mi">1</span> <span class="k">do</span>
<span class="n">post_via_redirect</span> <span class="n">users_path</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="s2">"Example User"</span><span class="p">,</span>
<span class="ss">email</span><span class="p">:</span> <span class="s2">"[email protected]"</span><span class="p">,</span>
<span class="ss">password</span><span class="p">:</span> <span class="s2">"password"</span><span class="p">,</span>
<span class="ss">password_confirmation</span><span class="p">:</span> <span class="s2">"password"</span> <span class="p">}</span>
<span class="k">end</span>
<span class="hll"> <span class="c1"># assert_template 'users/show'</span>
</span><span class="hll"> <span class="c1"># assert is_logged_in?</span>
</span> <span class="k">end</span>
<span class="k">end</span>
</pre></div>
</div>
<p>如果现在注册,重定向后显示的页面如<a href="#fig-redirected-not-activated">图 10.4</a> 所示,而且会生成一封邮件,如<a href="#listing-account-activation-email">代码清单 10.23</a> 所示。注意,在开发环境中并不会真发送邮件,不过能在服务器的日志中看到(可能要往上滚动才能看到)。<a href="#email-in-production">10.3 节</a>会介绍如何在生产环境中发送邮件。</p>
<div id="listing-account-activation-email" data-type="listing">
<h5><span class="title-label">代码清单 10.23</span>:在服务器日志中看到的账户激活邮件</h5>
<div class="highlight language-text"><pre>Sent mail to [email protected] (931.6ms)
Date: Wed, 03 Sep 2014 19:47:18 +0000
From: [email protected]
Message-ID: <540770474e16_61d3fd1914f4cd0300a0@mhartl-rails-tutorial-953753.mail>
Subject: Account activation
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_5407704656b50_61d3fd1914f4cd02996a";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_5407704656b50_61d3fd1914f4cd02996a
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Hi Michael Hartl,
Welcome to the Sample App! Click on the link below to activate your account:
http://rails-tutorial-c9-mhartl.c9.io/account_activations/
fFb_F94mgQtmlSvRFGsITw/edit?email=michael%40michaelhartl.com
----==_mimepart_5407704656b50_61d3fd1914f4cd02996a
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<h1>Sample App</h1>
<p>Hi Michael Hartl,</p>
<p>
Welcome to the Sample App! Click on the link below to activate your account:
</p>
<a href="http://rails-tutorial-c9-mhartl.c9.io/account_activations/
fFb_F94mgQtmlSvRFGsITw/edit?email=michael%40michaelhartl.com">Activate</a>
----==_mimepart_5407704656b50_61d3fd1914f4cd02996a--
</pre></div>
</div>
<div id="fig-redirected-not-activated" class="figure"><img src="images/chapter10/redirected_not_activated.png" alt="redirected not activated" /><div class="figcaption"><span class="title-label">图 10.4</span>:注册后显示的首页,有一个提醒激活的消息</div></div>
</section>
<section data-type="sect2" id="activating-the-account">
<h2><span class="title-label">10.1.3</span> 激活账户</h2>
<p>现在可以正确生成电子邮件了(<a href="#listing-account-activation-email">代码清单 10.23</a>),接下来我们要编写 <code>AccountActivationsController</code> 中的 <code>edit</code> 动作,激活用户。<a href="#account-activation-mailer-method">10.1.2 节</a>说过,激活令牌和电子邮件地址可以分别通过 <code>params[:id]</code> 和 <code>params[:email]</code> 获取。参照密码(<a href="chapter8.html#listing-find-authenticate-user">代码清单 8.5</a>)和记忆令牌(<a href="chapter8.html#listing-persistent-current-user">代码清单 8.36</a>)的实现方式,我们计划使用下面的代码查找和认证用户:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><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">:email</span><span class="o">]</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">authenticated?</span><span class="p">(</span><span class="ss">:activation</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>
</pre></div>
</div>
<p>(稍后会看到,上述代码还缺一个判断条件。看看你能否猜到缺了什么。)</p>
<p>上述代码使用 <code>authenticated?</code> 方法检查账户激活的摘要和指定的令牌是否匹配,但是现在不起作用,因为 <code>authenticated?</code> 方法是专门用来认证记忆令牌的(<a href="chapter8.html#listing-authenticated-p">代码清单 8.33</a>):</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="c1"># 如果指定的令牌和摘要匹配,返回 true</span>
<span class="k">def</span> <span class="nf">authenticated?</span><span class="p">(</span><span class="n">remember_token</span><span class="p">)</span>
<span class="k">return</span> <span class="kp">false</span> <span class="k">if</span> <span class="n">remember_digest</span><span class="o">.</span><span class="n">nil?</span>
<span class="no">BCrypt</span><span class="o">::</span><span class="no">Password</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">remember_digest</span><span class="p">)</span><span class="o">.</span><span class="n">is_password?</span><span class="p">(</span><span class="n">remember_token</span><span class="p">)</span>
<span class="k">end</span>
</pre></div>
</div>
<p>其中,<code>remember_digest</code> 是用户模型的属性,在模型内,我们可以将其改写成:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="nb">self</span><span class="o">.</span><span class="n">remember_digest</span>
</pre></div>
</div>
<p>我们希望以某种方式把这个值变成“变量”,这样才能调用 <code>self.activation_token</code>,而不是把合适的参数传给 <code>authenticated?</code> 方法。</p>
<p>我们要使用的解决方法涉及到“元编程”(metaprogramming),意思是用程序编写程序。(元编程是 Ruby 最强大的功能,Rails 中很多“神奇”的功能都是通过元编程实现的。)这里的关键是强大的 <code>send</code> 方法。这个方法的作用是在指定的对象上调用指定的方法。例如,在下面的控制台会话中,我们在一个 Ruby 原生对象上调用 <code>send</code> 方法,获取数组的长度:</p>
<div data-type="listing">
<div class="highlight language-irb"><pre><span class="go">$ rails console</span>
<span class="gp">>> </span><span class="n">a</span> <span class="o">=</span> <span class="o">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="o">]</span>
<span class="gp">>> </span><span class="n">a</span><span class="o">.</span><span class="n">length</span>
<span class="go">=> 3</span>
<span class="gp">>> </span><span class="n">a</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="ss">:length</span><span class="p">)</span>
<span class="go">=> 3</span>
<span class="gp">>> </span><span class="n">a</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s1">'length'</span><span class="p">)</span>
<span class="go">=> 3</span>
</pre></div>
</div>
<p>可以看出,把 <code>:length</code> 符号或者 <code>'length'</code> 字符串传给 <code>send</code> 方法的作用和在对象上直接调用 <code>length</code> 方法的作用一样。再看一个例子,获取数据库中第一个用户的 <code>activation_digest</code> 属性:</p>
<div data-type="listing">
<div class="highlight language-irb"><pre><span class="gp">>> </span><span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">first</span>
<span class="gp">>> </span><span class="n">user</span><span class="o">.</span><span class="n">activation_digest</span>
<span class="go">=> "$2a$10$4e6TFzEJAVNyjLv8Q5u22ensMt28qEkx0roaZvtRcp6UZKRM6N9Ae"</span>
<span class="gp">>> </span><span class="n">user</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="ss">:activation_digest</span><span class="p">)</span>
<span class="go">=> "$2a$10$4e6TFzEJAVNyjLv8Q5u22ensMt28qEkx0roaZvtRcp6UZKRM6N9Ae"</span>
<span class="gp">>> </span><span class="n">user</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s1">'activation_digest'</span><span class="p">)</span>
<span class="go">=> "$2a$10$4e6TFzEJAVNyjLv8Q5u22ensMt28qEkx0roaZvtRcp6UZKRM6N9Ae"</span>
<span class="hll"><span class="gp">>> </span><span class="n">attribute</span> <span class="o">=</span> <span class="ss">:activation</span>
</span><span class="hll"><span class="gp">>> </span><span class="n">user</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">attribute</span><span class="si">}</span><span class="s2">_digest"</span><span class="p">)</span>
</span><span class="hll"><span class="go">=> "$2a$10$4e6TFzEJAVNyjLv8Q5u22ensMt28qEkx0roaZvtRcp6UZKRM6N9Ae"</span>
</span></pre></div>
</div>
<p>注意最后一种调用方式,我们定义了一个 <code>attribute</code> 变量,其值为符号 <code>:activation</code>,然后使用字符串插值构建传给 <code>send</code> 方法的参数。<code>attribute</code> 变量的值使用字符串 <code>'activation'</code> 也行,不过符号更便利。不管使用什么,插值后,<code>"#{attribute}_digest"</code> 的结果都是 <code>"activation_digest"</code>。(<a href="chapter7.html#the-flash">7.4.2 节</a>介绍过,插值时会把符号转换成字符串。)</p>
<p>基于上述对 <code>send</code> 方法的介绍,我们可以把 <code>authenticated?</code> 方法改写成:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="k">def</span> <span class="nf">authenticated?</span><span class="p">(</span><span class="n">remember_token</span><span class="p">)</span>
<span class="n">digest</span> <span class="o">=</span> <span class="nb">self</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s1">'remember_digest'</span><span class="p">)</span>
<span class="k">return</span> <span class="kp">false</span> <span class="k">if</span> <span class="n">digest</span><span class="o">.</span><span class="n">nil?</span>
<span class="no">BCrypt</span><span class="o">::</span><span class="no">Password</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">digest</span><span class="p">)</span><span class="o">.</span><span class="n">is_password?</span><span class="p">(</span><span class="n">remember_token</span><span class="p">)</span>
<span class="k">end</span>
</pre></div>
</div>
<p>以此为模板,我们可以为这个方法增加一个参数,代表摘要的名字,然后再使用字符串插值,扩大这个方法的用途:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="k">def</span> <span class="nf">authenticated?</span><span class="p">(</span><span class="n">attribute</span><span class="p">,</span> <span class="n">token</span><span class="p">)</span>
<span class="n">digest</span> <span class="o">=</span> <span class="nb">self</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">attribute</span><span class="si">}</span><span class="s2">_digest"</span><span class="p">)</span>
<span class="k">return</span> <span class="kp">false</span> <span class="k">if</span> <span class="n">digest</span><span class="o">.</span><span class="n">nil?</span>
<span class="no">BCrypt</span><span class="o">::</span><span class="no">Password</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">digest</span><span class="p">)</span><span class="o">.</span><span class="n">is_password?</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>
<span class="k">end</span>
</pre></div>
</div>
<p>(我们把第二个参数的名字改成了 <code>token</code>,以此强调这个方法的用途更广。)因为这个方法在用户模型内,所以可以省略 <code>self</code>,得到更符合习惯写法的版本:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="k">def</span> <span class="nf">authenticated?</span><span class="p">(</span><span class="n">attribute</span><span class="p">,</span> <span class="n">token</span><span class="p">)</span>
<span class="n">digest</span> <span class="o">=</span> <span class="nb">send</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">attribute</span><span class="si">}</span><span class="s2">_digest"</span><span class="p">)</span>
<span class="k">return</span> <span class="kp">false</span> <span class="k">if</span> <span class="n">digest</span><span class="o">.</span><span class="n">nil?</span>
<span class="no">BCrypt</span><span class="o">::</span><span class="no">Password</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">digest</span><span class="p">)</span><span class="o">.</span><span class="n">is_password?</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>
<span class="k">end</span>
</pre></div>
</div>
<p>现在我们可以像下面这样调用 <code>authenticated?</code> 方法实现以前的效果:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><span class="n">user</span><span class="o">.</span><span class="n">authenticated?</span><span class="p">(</span><span class="ss">:remember</span><span class="p">,</span> <span class="n">remember_token</span><span class="p">)</span>
</pre></div>
</div>
<p>把修改后的 <code>authenticated?</code> 方法写入用户模型,如<a href="#listing-generalized-authenticated-p">代码清单 10.24</a> 所示。</p>
<div id="listing-generalized-authenticated-p" data-type="listing">
<h5><span class="title-label">代码清单 10.24</span>:用途更广的 <code>authenticated?</code> 方法 <span class="red">RED</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="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="c1"># 如果指定的令牌和摘要匹配,返回 true</span>
<span class="k">def</span> <span class="nf">authenticated?</span><span class="p">(</span><span class="n">attribute</span><span class="p">,</span> <span class="n">token</span><span class="p">)</span>
<span class="n">digest</span> <span class="o">=</span> <span class="nb">send</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">attribute</span><span class="si">}</span><span class="s2">_digest"</span><span class="p">)</span>
<span class="k">return</span> <span class="kp">false</span> <span class="k">if</span> <span class="n">digest</span><span class="o">.</span><span class="n">nil?</span>
<span class="no">BCrypt</span><span class="o">::</span><span class="no">Password</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="n">digest</span><span class="p">)</span><span class="o">.</span><span class="n">is_password?</span><span class="p">(</span><span class="n">token</span><span class="p">)</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-generalized-authenticated-p">代码清单 10.24</a> 的标题所示,测试组件无法通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 10.25</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>current_user</code> 方法(<a href="chapter8.html#listing-persistent-current-user">代码清单 8.36</a>)和摘要为 <code>nil</code> 的测试(<a href="chapter8.html#listing-test-authenticated-invalid-token">代码清单 8.43</a>)使用的都是旧版 <code>authenticated?</code>,期望传入的是一个参数而不是两个。因此,我们只需修改这两个地方,换用修改后的 <code>authenticated?</code> 方法就能解决这个问题,如<a href="#listing-generalized-current-user">代码清单 10.26</a> 和<a href="#listing-test-authenticated-invalid-token-updated">代码清单 10.27</a> 所示。</p>
<div id="listing-generalized-current-user" data-type="listing">
<h5><span class="title-label">代码清单 10.26</span>:在 <code>current_user</code> 中使用修改后的 <code>authenticated?</code> 方法 <span class="green">GREEN</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">current_user</span>
<span class="k">if</span> <span class="p">(</span><span class="n">user_id</span> <span class="o">=</span> <span class="n">session</span><span class="o">[</span><span class="ss">:user_id</span><span class="o">]</span><span class="p">)</span>
<span class="vi">@current_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="nb">id</span><span class="p">:</span> <span class="n">user_id</span><span class="p">)</span>
<span class="k">elsif</span> <span class="p">(</span><span class="n">user_id</span> <span class="o">=</span> <span class="n">cookies</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="p">)</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="nb">id</span><span class="p">:</span> <span class="n">user_id</span><span class="p">)</span>
<span class="hll"> <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">authenticated?</span><span class="p">(</span><span class="ss">:remember</span><span class="p">,</span> <span class="n">cookies</span><span class="o">[</span><span class="ss">:remember_token</span><span class="o">]</span><span class="p">)</span>
</span> <span class="n">log_in</span> <span class="n">user</span>
<span class="vi">@current_user</span> <span class="o">=</span> <span class="n">user</span>
<span class="k">end</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>
<div id="listing-test-authenticated-invalid-token-updated" data-type="listing">
<h5><span class="title-label">代码清单 10.27</span>:在 <code>UserTest</code> 中使用修改后的 <code>authenticated?</code> 方法 <span class="green">GREEN</span></h5>
<div class="source-file">test/models/user_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">UserTest</span> <span class="o"><</span> <span class="no">ActiveSupport</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="no">User</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="nb">name</span><span class="p">:</span> <span class="s2">"Example User"</span><span class="p">,</span> <span class="ss">email</span><span class="p">:</span> <span class="s2">"[email protected]"</span><span class="p">,</span>
<span class="ss">password</span><span class="p">:</span> <span class="s2">"foobar"</span><span class="p">,</span> <span class="ss">password_confirmation</span><span class="p">:</span> <span class="s2">"foobar"</span><span class="p">)</span>
<span class="k">end</span>