`
jiajie0531
  • 浏览: 27549 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Active Record Validations 3 Common Validation Options 通常的校验选项

阅读更多

version: Rails 4.1

3 Common Validation Options 通常的校验选项

下面是一些通常的校验选项:

 

3.1 :allow_nil 

当值被检查到是 nil 的时候,:allow_nil 选项跳过校验。

classCoffee < ActiveRecord::Base

  validates :size, inclusion: { in: %w(small medium large),

    message: "%{value} is not a valid size"}, allow_nil: true

end

 

3.2 :allow_blank

:allow_blank 选项和 :allow_nil 选项很类似。如果属性的值是 blank? 那么这个选项将会让校验通过, 例如类似于 nil 或者一个空的字符串。

 

classTopic < ActiveRecord::Base

  validates :title, length: { is: 5}, allow_blank: true

end

 

Topic.create(title: "").valid?  # => true

Topic.create(title: nil).valid? # => true

3.3 :message

正如你所看到的,:message 选项让你声明一个消息,当校验失败的时候,将会被增加到错误信息的集合中。当这个选项没有被使用时,Active Record 将会使用各自的默认错误信息对于每一个校验的helper。

 

3.4 :on

:on 选项让你声明校验该何时发生。对于所有内建的校验helper默认行为都是为save而运行的(当你创建一个新的数据记录行和当你更新它时)。如果你想要改变它,当一条新的数据记录行被创建时,你可以只使用 on: :create 来运行校验。当一个数据记录行被更新时,只要使用 on: :update 来运行校验即可。

 

classPerson < ActiveRecord::Base

  # it will be possible to update email with a duplicated value

  validates :email, uniqueness: true, on: :create

 

  # it will be possible to create the record with a non-numerical age

  validates :age, numericality: true, on: :update

 

  # the default (validates on both create and update)

  validates :name, presence: true

end

 

 

 

original url: http://guides.rubyonrails.org/active_record_validations.html#common-validation-options

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics