名字定为“sexy validations” 的原因是:此种方法提供了1种更简洁的校验方式和重用已有的验证类.此种处理方式与 sexy migrations的工作方式类似.
使用已存在Rails校验的简单例子,如下:
class Film <; ActiveRecord::Base validates :title, :presence => true, :uniqueness => true, :length => { :maximum => 100 } validates :budget, :presence => true, :length => { :within => 1..10000000 } end上述为一种"sexy"方式;
当使用自定义验证时,"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
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