Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate uniquness across models in MongoDB with Rails?

In my rails app, I use MongoDB. I have 4 models including the admin. All the entities have an email address. I need to make validation to make sure that the email is unique for all the models.

Is there a simpler/better way to do that other than searching for the email in every model?

like


 def email_uniquness_across_models(email)
    User.where(email: email).exists? ||
      Admin.where(email: email).exists? ||
      Transporter.where(email: email).exists? ||
      Company.where(email: email).exists?
  end

like image 403
kerolloz Avatar asked Nov 07 '22 06:11

kerolloz


1 Answers

In case you are set on keeping the models as they are, and have to keep the uniqness of emails between 4 collection, I would create an Email model in its own collection with a unique index defined on the email field:

class Email
  include Mongoid::Document

  field :email, type: String
  index({email: 1}, {unique: true})
end

This way all you have to do is to try and create that Email model. If you succeed you can go ahead and create the specific model you want, knowing that the email is unique across all models. (this suggestion is similar to what @huzaifa-saifuddin suggested, but without combining all the models into one collection)

Then the uniqueness method definition would have a single call to the DB and would look like this:

def email_uniquness_across_models(email)
  Email.create(email: email)
  true
rescue
  false
end

IMHO it is better to have one call to the DB that ensure uniqueness than 4 calls that will ensure uniqueness most of the times.

This implementation will ensure the uniqueness but you will also have to handle failures - meaning handle the case where the subsequent model creation failed and you now need to remove the Email document so the specific email will be available.

like image 106
Udi Cohen Avatar answered Nov 12 '22 14:11

Udi Cohen