1. validates_presence_of
validates_presence_of()方法是一个标准的Rails验证器,它会检查指定字段存在、并且值不为空。
用法,例如:(C:\Users\Tony\Desktop\rails\deopt\app\models\product.rb)
class Product < ActiveRecord::Base
validates_presence_of :title, :description, :image_url
end
2. validates_numericality_of
来检查价格是否是合法的数值。
3. validate(只定义验证)
例如:
class Product < ActiveRecord::Base
validates_presence_of :title, :description, :image_url
validates_numericality_of :price
validate :price_must_be_at_least_a_cent
protected
def price_must_be_at_least_a_cent
errors.add(:price, 'should be at least 0.01' ) if price.nil? || price < 0.01
end
end
4. validates_uniqueness_of
确保数据的唯一性:
validates_uniqueness_of :title
5. validates_format_of
validates_format_of()验证格式是否正确:
validates_format_of :image_url,
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG or PNG image.'