在model中添加了基础的校验逻辑,title 字段不能为空,不能小于5个字符
保存成功就直接显示,如果保存失败,就重绘 new 页面,new 页面中加入了对错误信息的显示
并且将之前的值放到新的窗口中,要求继续输入,准备重新提交
更新文章
定义 edit 方法,并且创建 edit 视图
代码语言:javascript复制[root@h202 blog]# vim app/controllers/articles_controller.rb
[root@h202 blog]# cat app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
# render plain: params[:article].inspect
# @article = Article.new(params[:article])
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def show
@article = Article.find(params[:id])
end
def index
@articles = Article.all
end
private
def article_params
params.require(:article).permit(:title,:text)
end
end
[root@h202 blog]# vim app/views/articles/edit.html.erb
[root@h202 blog]# cat app/views/articles/edit.html.erb
<h1>Editing article</h1>
<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
[root@h202 blog]#