uniqueness验证属性值是否是唯一

2018-09-21  本文已影响0人  rubyboy

这个辅助方法在保存对象之前验证属性值是否是唯一的。该方法不会在数据库中创建唯一性约束,所以有可

能两次数据库连接创建的记录具有相同的字段值。为了避免出现这种问题,必须在数据库的字段上建立唯一

性索引。

    class Account < ApplicationRecord

      validates :email, uniqueness: true

   end

这个验证会在模型对应的表中执行一个 SQL 查询,检查现有的记录中该字段是否已经出现过相同的值。:scope 选项用于指定检查唯一性时使用的一个或多个属性:

    class Holiday < ApplicationRecord
      validates :name, uniqueness: { scope: :year,

        message: "should happen once per year" }   
   end

如果想确保使用 :scope 选项的唯一性验证严格有效,必须在数据库中为多列创建唯一性索引。

例子如下:

model中的验证:

class Poi < ApplicationRecord

  validates :lng, presence: { message: "lng不能为空" },

    uniqueness: {scope: :lat, message: "坐标已被占用"},

    format: {:with => /\d+[.]\d+/, message: '格式不正确, eg: 66.6'}

  validates :lat, presence: { message: "lat不能为空" },

    format: {:with => /\d+[.]\d+/, message: '格式不正确, eg: 66.6'}

end

数据库中建立唯一性索引:

class CreatePoi < ActiveRecord::Migration[5.2]

  def change

    create_table :pois do |t|

    t.string :lng, null: false

    t.string :lat, null: false

    t.timestamps null: false

    end

    add_index :pois, [:lng,:lat], unique: true, name: :unique_coordinate_constraint

  end

end

上一篇下一篇

猜你喜欢

热点阅读