2.5 练习
最后更新于:2022-04-01 22:28:05
# 2.5 练习
电子书中有练习的答案,如果想阅读参考答案,请[购买电子书](http://railstutorial-china.org/#purchase)。
1. [代码清单 2.18](#listing-validates-content-presence) 为微博内容添加了一个存在性验证,以此确保微博不能为空。验证这个规则确实能实现如[图 2.19](#fig-micropost-content-cant-be-blank) 所示的效果。
2. 修改[代码清单 2.19](#listing-toy-user-presence-valications),把 `FILL_IN` 改成合适的代码,验证用户模型的 `name` 和 `email` 属性都存在([图 2.20](#fig-user-presence-validations))。
##### 代码清单 2.18:微博内容的存在性验证
app/models/micropost.rb
```
class Micropost < ActiveRecord::Base
belongs_to :user
validates :content, length: { maximum: 140 },
presence: true end
```
##### 代码清单 2.19:在用户模型中加入存在验证
app/models/user.rb
```
class User < ActiveRecord::Base
has_many :microposts
validates FILL_IN, presence: true validates FILL_IN, presence: true end
```
图 2.19:微博模型存在性验证的效果图 2.20:用户模型中存在性验证的效果
';