rails 数据验证(rails guides学习笔记)

来源:互联网 发布:java 线程锁活锁 死锁 编辑:程序博客网 时间:2024/06/07 06:28

数据验证目的:保证存储进数据库的是有效数据

数据在何时验证?

Active Record 对象分为两种:一种在数据库中有对应的记录,一种没有。新建的对象(例如,使用 new 方法)还不属于数据库。在对象上调用 save 方法后,才会把对象存入相应的数据库表。Active Record 使用实例方法 new_record? 判断对象是否已经存入数据库。

t=Teacher.new(name:"John")t.new_record? #truet.savet.new_record?#false


下列方法会触发数据验证,如果验证失败就不把对象存入数据库:

  • create
  • create!
  • save
  • save!
  • update
  • update!

 跳过验证

下列方法会跳过验证,不管验证是否通过都会把对象存入数据库,使用时要特别留意。

  • decrement!
  • decrement_counter
  • increment!
  • increment_counter
  • toggle!
  • touch
  • update_all
  • update_attribute
  • update_column
  • update_columns
  • update_counters

注意

1、使用 save 时如果传入 validate: false 参数,也会跳过验证。使用时要特别留意。

  • save(validate: false)

2、验证过程产生错误,Rails 不会保存对象

t=Teacher.newt.valid?#false,触发数据验证,对=> true,错=> falset.errors.messages#返回一个错误集合t.invalid?#触发数据验证,与valid?方法相反t.errors[:name]#查看是哪个验证导致属性无效的



数据验证辅助方法

acceptance #检查表单提交时,用户界面中的复选框是否被选中


  validates:terms_of_service, acceptance: { message: 'must be abided'}

validates_associated #如果模型和其他模型有关联,而且关联的模型也要验证,要使用这个辅助方法

  has_many:books
  validates_associated:books

#支持任何类型关联,不能在两端同时使用

confirmation #要检查两个文本字段的值是否完全相同

  validates:email, confirmation: true  #validates:email, confirmation: { case_sensitive: false}使用 :case_sensitive 选项指定确认时是否区分大小写。这个选项的默认值是 true。  validates:email_confirmation, presence: true

在视图模板中可以这么写:

<%=text_field:person,:email%>
<%=text_field:person,:email_confirmation%>

length

  validates :name, length: { minimum: 2 }  validates :bio, length: { maximum: 500 }  validates :password, length: { in: 6..20 }  validates :registration_number, length: { is: 6 }

  • minimum:属性的值不能比指定的长度短;
  • maximum:属性的值不能比指定的长度长;
  • in(或 :within):属性值的长度在指定值之间。该选项的值必须是一个范围;
  • is:属性值的长度必须等于指定值;


默认的错误消息根据长度验证类型而有所不同,还是可以 :message 定制。定制消息时,可以使用 :wrong_length:too_long 和 :too_short 选项,%{count} 表示长度限制的值。
  validates :bio, length: { maximum: 1000,    too_long: "%{count} characters is the maximum allowed" }




  validates:points, numericality: true  validates:games_played, numericality: { only_integer: true}



  • greater_than:属性值必须比指定的值大。该选项默认的错误消息是“must be greater than %{count}”;
  • greater_than_or_equal_to:属性值必须大于或等于指定的值。该选项默认的错误消息是“must be greater than or equal to %{count}”;
  • equal_to:属性值必须等于指定的值。该选项默认的错误消息是“must be equal to %{count}”;
  • less_than:属性值必须比指定的值小。该选项默认的错误消息是“must be less than %{count}”;
  • less_than_or_equal_to:属性值必须小于或等于指定的值。该选项默认的错误消息是“must be less than or equal to %{count}”;
  • odd:如果设为 true,属性值必须是奇数。该选项默认的错误消息是“must be odd”;
  • even:如果设为 true,属性值必须是偶数。该选项默认的错误消息是“must be even”;

uniqueness #保存对象之前验证属性值是否是唯一

  validates:email, uniqueness: true




scope 选项可以指定其他属性,用来约束唯一性验证:
  validates:name, uniqueness: { scope: :year,    message:"should happen once per year" }




case_sensitive 选项,指定唯一性验证是否要区分大小写,默认值为 true

  validates:name, uniqueness: { case_sensitive: false}

format

这个帮助方法检查属性的值是否匹配 :with 选项指定的正则表达式。

class Product < ActiveRecord::Base
  validates:legacy_code, format: { with: /\A[a-zA-Z]+\z/,
    message:"only allows letters"}
end

allow_nil:

指定 allow_nil: 选项后,如果要验证的值为 nil 就会跳过验证。

classCoffee < ActiveRecord::Base  validates:size, inclusion: { in: %w(small medium large),    message:"%{value} is not a valid size" }, allow_nil: trueend



allow_blank:

allow_blank: 和 allow_nil: 类似。如果要验证的值为空(调用 blank? 方法,例如 nil 或空字符串),就会跳过验证。

classTopic < ActiveRecord::Base  validates:title, length: { is: 5}, allow_blank: trueend Topic.create(title:"").valid? # => trueTopic.create(title:nil).valid?# => true

message:

如果验证失败,会把 :message 选项指定的字符串添加到 errors 集合中。如果没指定这个选项,Active Record 会使用各种验证帮助方法的默认错误消息。

on:

on: :xxx 选项指定什么时候做验证。所有内建的验证帮助方法默认都在保存时(新建记录或更新记录)做验证。如果想修改,可以使用 on: :create,指定只在创建记录时做验证;或者使用 on: :update,指定只在更新记录时做验证。

  # 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




原创粉丝点击