在Rails中向现有模型添加验证

时间:2022-06-15 07:34:44

I would like to add a :presence and :uniqueness validation to a model in Rails. I'm using MongoDB and the Mongoid gem.

我想在Rails中为模型添加一个:presence and:unique validation。我用的是MongoDB和Mongoid gem。

I have a model that is already in use and have existing records in the DB. I'd like to add a new :field and then add validations for :presence and :uniqueness for the field.

我有一个已经在使用的模型,并且在DB中已有记录。我想添加一个新的:字段,然后为:presence和:unique添加验证。

I know that by default, any existing records will simply add the :field and the result will be null unless I specify a :default.

我知道默认情况下,任何现有记录都只会添加:字段,结果将为null,除非我指定:default。

My question is, since I want this new :field to be unique, will this cause an error for the existing records in the DB that will be null? Will I lose these records or does Rails just apply the validations to the new records?

我的问题是,既然我想要这个新的:字段是唯一的,这是否会导致DB中现有记录的错误为null?我将丢失这些记录,还是Rails仅仅将验证应用到新记录?

1 个解决方案

#1


2  

Rails/AciveRecord will not ignore or delete your old records...

Rails/AciveRecord不会忽略或删除您的旧记录……

Validations work as follows: they are only used/checked when you try to write stuff to the database, e.g. when you create a new record or when you update a record. So in your case you will get validation errors when you try to update an old record without adding the new required fields.

验证工作如下:它们只在您尝试向数据库写入内容时使用/检查,例如当您创建新记录或更新记录时。因此,在您的示例中,当您试图更新旧记录而不添加新的必需字段时,将会出现验证错误。

I suggest that you try to clean up your database when adding the new fields (meaning adding sensible defaults to old records for the new required fields).

我建议您尝试在添加新字段时清理数据库(意味着为新必需字段在旧记录中添加合理的默认值)。

#1


2  

Rails/AciveRecord will not ignore or delete your old records...

Rails/AciveRecord不会忽略或删除您的旧记录……

Validations work as follows: they are only used/checked when you try to write stuff to the database, e.g. when you create a new record or when you update a record. So in your case you will get validation errors when you try to update an old record without adding the new required fields.

验证工作如下:它们只在您尝试向数据库写入内容时使用/检查,例如当您创建新记录或更新记录时。因此,在您的示例中,当您试图更新旧记录而不添加新的必需字段时,将会出现验证错误。

I suggest that you try to clean up your database when adding the new fields (meaning adding sensible defaults to old records for the new required fields).

我建议您尝试在添加新字段时清理数据库(意味着为新必需字段在旧记录中添加合理的默认值)。