简体   繁体   English

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

[英]Adding validations to existing model in Rails

I would like to add a :presence and :uniqueness validation to a model in Rails. 我想在Rails中为模型添加一个:presence和:uniqueness validation。 I'm using MongoDB and the Mongoid gem. 我正在使用MongoDB和Mongoid gem。

I have a model that is already in use and have existing records in the DB. 我有一个已经在使用的模型,并且在DB中有现有记录。 I'd like to add a new :field and then add validations for :presence and :uniqueness for the field. 我想添加一个新的:字段,然后添加验证:存在和:字段的唯一性。

I know that by default, any existing records will simply add the :field and the result will be null unless I specify a :default. 我知道默认情况下,任何现有记录都只会添加:field,结果将为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? 我的问题是,既然我希望这个新的:字段是唯一的,这会导致DB中现有记录的错误是否为空? Will I lose these records or does Rails just apply the validations to the new records? 我是否会丢失这些记录,或者Rails是否只将验证应用于新记录?

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, eg 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). 我建议您在添加新字段时尝试清理数据库(意味着为新的必填字段添加旧记录的合理默认值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM