列表页面多出来两个链接,点击 【New article】
成功跳转到了添加页面,随便输入点什么,提交
自动跳转到了显示页面,点击【Back】
跳转回了所有列表页面
Tip: 之所以每做一次修改都能直接生效,是因为在开发模式下(默认),每次请求 Rails 都会自动重新加载程序,因此修改之后无需重启服务器
数据验证
我们常常有对输入进行校验的需求,以避免接受到了无效或不合规范的数据
代码语言:javascript复制[root@h202 blog]# vim app/models/article.rb
[root@h202 blog]# cat app/models/article.rb
class Article < ActiveRecord::Base
validates :title, presence: true, length: { minimum: 5 }
end
[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 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/new.html.erb
[root@h202 blog]# cat app/views/articles/new.html.erb
<h1>Test blog http://soft.dog/</h1>
<%= form_for :article, url: articles_path 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]#