Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding validations to existing model in Rails

I would like to add a :presence and :uniqueness validation to a model in Rails. I'm using MongoDB and the 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.

I know that by default, any existing records will simply add the :field and the result will be null unless I specify a :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?

like image 248
GRorange Avatar asked Dec 27 '25 16:12

GRorange


1 Answers

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

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).

like image 164
severin Avatar answered Dec 30 '25 04:12

severin