Ii. Use the data check function provided by rails3.0 to check input data

Source: Internet
Author: User

Next, go to the previous article and open the app/models/product. rb file.

1 class Product < ActiveRecord::Base
2 end

In this file, you can add some statements to restrict the input data.

validates :title, :description, :image_url, :presence => true

This statement indicates that the constraints for opening fields are non-empty. In this case, check whether the title, description, image_url, and these fields are non-empty,

Come,

validates :price, :numericality => {:greater_than_or_equal_to => 0.01}

This statement requires that the price value is greater than or equal to 0.01,

Come back

validates :title, :uniqueness => true

This statement verifies that the title field cannot be repeated,

1 validates :image_url, :format => {
2 :with => %r{\.(gif|jpg|png)$}i,
3 :message => 'must be a URL for GIF, JPG or PNG image.'
4 }

Finally, this is to constrain image_url and process it through a regular expression. The format must be gif/jpg/png. The criterion is that the last decimal point must be the extension,

OK, I'm done, so the complete code should be like this.

class Product < ActiveRecord::Base  validates :title, :description, :image_url, :presence => true  validates :price, :numericality => {:greater_than_or_equal_to => 0.01}  validates :title, :uniqueness => true  validates :image_url, :format => {    :with    => %r{\.(gif|jpg|png)$}i,    :message => 'must be a URL for GIF, JPG or PNG image.'  }end

You can try to open the http: // localhost: 3000/products Page and directly press submit? Haha

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.