Rails表单验证 #
一、服务器验证 #
1.1 模型验证 #
ruby
class Article < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true
end
1.2 控制器处理 #
ruby
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article, notice: '创建成功'
else
render :new, status: :unprocessable_entity
end
end
二、错误显示 #
2.1 显示错误消息 #
erb
<% if @article.errors.any? %>
<div class="alert alert-danger">
<h4><%= pluralize(@article.errors.count, 'error') %></h4>
<ul>
<% @article.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
三、总结 #
3.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 模型验证 | validates方法 |
| 错误对象 | errors |
| 错误消息 | full_messages |
3.2 下一步 #
现在你已经掌握了表单验证,接下来让我们学习 文件上传,深入了解Rails的文件上传!
最后更新:2026-03-28