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