📜  Ruby on Rails验证

📅  最后修改于: 2021-01-12 02:52:34             🧑  作者: Mango

Rails验证

Rails验证为每个Active Record模型类定义有效状态。它们用于确保仅将有效的详细信息输入到数据库中。 Rails使向模型类添加验证变得容易,并且还允许您创建自己的验证方法。使用内置的验证DSL,您可以执行多种验证。

如果Active Record模型类的验证失败,则将其视为错误。每个Active Record模型类都维护一个错误集合,当发生验证错误时,这些错误集合会向用户显示适当的错误信息。

Rails内置的验证方法

Method Description
validates_acceptance_of This validation is done by the user to accept a terms of service agreement by checking in a check box
validates_associated Validates whether associated objects are all valid themselves. Work with any kind of association.
validates_confirmation_of It validates whether a user has entered matching information like password or email in second entry field.
validates_each Validates each attribute against a block.
validates_exclusion_of Validates that an attribute is not in a particular enumerable object.
validates_format_of Validates value of an attribute using a regular expression to insure it is of correct format.
validates_inclusion_of Validates whether value of an attribute is available in a particular enumerable object.
validates_length_of Validates that length of an attribute matches length restrictions specified.
validates_numericality_of Validates whether an attribute is numeric.
validates_presence_of Validates that attribute is not blank.
validates_size_of This is an alias for validates_length_of
validates_uniqueness_of Validates that an attribute is unique in the database.

跳过验证

以下Rails方法将跳过验证,并将对象保存到数据库中,而不管其有效性如何。应谨慎使用它们。

  • 递减!
  • 递减计数器
  • 增量!
  • 增量计数器
  • 切换!
  • 触摸
  • 全部更新
  • update_attribute

有效?无效吗?

保存Active Record对象之前,Rails会进行验证。如果产生任何错误,则不保存对象。

有效吗?触发您的验证,如果未发现错误,则返回true,否则返回false。

例:

class Person < ApplicationRecord
??validates :name, presence: true
end
?
Person.create(name: "John Cena").valid? # => true
Person.create(name: nil).valid? # => false

无效吗?是有效的反向吗?它触发您的验证,如果无效则返回true,否则返回false。