名字定为
“sexy validations” 的原因是:此种方法提供了1种更简洁的校验方式和重用已有的验证类.此种处理方式与 sexy migrations的工作方式类似.
上述为一种"sexy"方式;
在Rails中,所有的验证函数及常用的模型函数均被集成到了 ActiveModel中,因此可以使用validations and Validator类来代替ActiveRecord,例如:
使用已存在Rails校验的简单例子,如下:
- class Film <; ActiveRecord::Base
- validates :title, :presence => true, :uniqueness => true, :length => { :maximum => 100 }
- validates :budget, :presence => true, :length => { :within => 1..10000000 }
- end
当使用自定义验证时,"validates"方法的作用显现出来了:
- class IntenseFilmTitleValidator <; ActiveModel::EachValidator
- def validate_each(record, attribute, value)
- record.errors[attribute] <;<; "must start with 'The'" unless value =~ /^The/
- end
- end
- class SpendValidator <; ActiveModel::EachValidator
- def validate_each(record, attribute, value)
- spend = case options[:size]
- when :big then 100000000
- when :small then 100000
- end
- record.errors[attribute] <;<; "must not exceed #{spend} " if value > spend
- end
- end
- class Film <; ActiveRecord::Base
- validates :title, :presence => true, :intense_film_title => true
- validates :budget, :spend => { :size => :big } # using custom options
- end
在Rails中,所有的验证函数及常用的模型函数均被集成到了 ActiveModel中,因此可以使用validations and Validator类来代替ActiveRecord,例如:
- class EmailValidator <; ActiveModel::EachValidator
- def validate_each(record, attribute, value)
- record.errors[attribute] <;<; (options[:message] || "is not an email") unless
- value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
- end
- end
- class Person
- include ActiveModel::Validations
- attr_accessor :name, :email
- validates :name, :presence => true, :length => { :maximum => 100 }
- validates :email, :presence => true, :email => true
- end