Here simply add a few validations, non-empty, minimum length, unique
Modifying a model
Modify the App/models/post.rb file as follows:
class Post < ActiveRecord::Base
#attr_accessible :title, :content
validates :title, :context, :presence => true
validates :title, :length => { :minimum =>2}
validates :title, :uniqueness => { :message =>‘Already taken‘}
end
At this time to run the service, modify/New model, when nothing is filled, can not be submitted, nor error.
What's the reason?
Because you didn't show the error message.
Modify views
Modify the App/views/posts/new.html.erb file as follows:
<h1>Add a new post</h1>
<%= form_for @post do |f| %>
<%if @post.errors.any? %>
<h3>Errors</h3>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%=msg%></li>
<% end %>
</ul>
<%end%>
<p>
<%= f.label :title%><br/>
<%= f.text_field :title%>
</p>
<p>
<%= f.label :context%><br/>
<%= f.text_area :context%>
</p>
<p>
<%= f.submit "New Post"%>
</p>
Add
<%if @post.errors.any? %>
<h3>Errors</h3>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%=msg%></li>
<% end %>
</ul>
<%end%>
For app / views / posts / edit.html.erb do the same.
Run service
rails s -b 192.168.xxx.xxx -p 3000, add a record, and submit directly without filling in any messages. The verification message is as follows:
Reprinted please indicate this article from: http://www.cnblogs.com/Tommy-Yu/p/4143036.html, thank you!
[ruby on rails] Follow me (10) Data input verification