[Ruby on Rails] Learn from me (10) Data Entry validation

Source: Internet
Author: User
Tags ruby on rails



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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.