rails3.0新的验证方法
rails3.0新的验证方法已经从Active Model中抽取出来,它接受一个属性和哈稀验证选项,不在像3.0以前针对每个属性使用一个验证方法,极大的简化了验证流程.
以前的方法虽然还在,但不推荐使用了,因为我们够懒.
下面我们先来看一个简单的示例:
class Person < ActiveRecord::Base
validates :email, :presence => true
end
1. :acceptance => Boolean
2. :confirmation => Boolean
3. :exclusion => { :in => Ennumerable }
3. :inclusion => { :in => Ennumerable }
4. :format => { :with => Regexp }
5. :length => { :minimum => Fixnum, maximum => Fixnum, }
6. :numericality => Boolean
7. :presence => Boolean
8. :uniqueness => Boolean
更容易使用的验证选项,让验证更加轻松,我们以一个比较完整的验证用户名和电子邮件作为示例:
# app/models/person.rb
class User < ActiveRecord::Base
validates :name, :presence => true,
:length => {:minimum => 1, :maximum => 254}
validates :email, :presence => true,
:length => {:minimum => 3, :maximum => 254},
:uniqueness => true,
:format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}
end
从示例中我们可以看到,模型的各个属性以及要进行何种验证,代码的可读性也得到了提升.
在了解rails 3.0验证方法的基本使用方法后,我们来看下一些更高级的应用.
当用户分为不同的等级,如游客,用户,客户等,它们共用preson模型,这时我们可以应用: validates_with
# app/models/person.rb class User < ActiveRecord::Base validates_with HumanValidator end # app/models/person.rb class Visitor < ActiveRecord::Base validates_with HumanValidator end # app/models/person.rb class Customer < ActiveRecord::Base validates_with HumanValidator end
然后在你项目的lib目录创建以下文件
class HumanValidator < ActiveModel::Validator
def validate(record)
record.errors[:base] << "This person is dead" unless check(human)
end
private
def check(record)
(record.age < 200) && (record.age > 0)
end
end
启动控制台,运行以下代码,你就会看到效果:
$ ./script/console
Loading development environment (Rails 3.0.pre)
>> u = User.new
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>
>> u.valid?
=> false
>> u.errors
=> #<OrderedHash {:base=>["This person is dead"]}>
浙公网安备 33010602011771号