Redundant Emails with Devise

This afternoon, I was asked by my friend about how to make email column allow redundant data with rails and devise. Honestly, I never did something like that before and I couldn’t imagine what kind of case he was trying to solve with that particular design.

What I advised him was try removing the unique index attached to email column. That’s actually an easy task, just generate a migration file and make a little change so the migration file will be like this

class RemoveEmailIndexOnUser < ActiveRecord::Migration
  def change
    remove_index :users, :email

Migrate it and boom! The index is now gone. In case, you still need the index, but don’t want it to be unique, you might have this code after the remove_index code.

add_index :users, :email

Now, you no longer have the column, then I told him to change the devise config. I think, with the change, it will be pretty similar like this (I only show some part of the config file)

config.authentication_keys = [ :username ]
config.case_insensitive_keys = [ :username ]
config.strip_whitespace_keys = [ :username ]

Now, I think you should be able to sign up with existing email…

No, wait! I still can’t sign up with existing email. How come!?

Aaah, I see! The culprit is :validateable.

So, if you go to the documentation, you’ll see this description.

Validatable creates all needed validations for a user email and password. It’s optional, given you may want to create the validations by yourself. Automatically validate if the email is present, unique and its format is valid. Also tests presence of password, confirmation and length.

With validateable, by default, it will validate email for its presence, uniqueness, and format validity. And password for its presence, length, confirmation presence, and confirmation similarity.

So, how can I have redundant emails without removing :validateable?

AFAIK, you still need to remove that, but the other way around is having your own validations for email and password. So, maybe you can have something like this in your model.

validates :email, presence: true
validates :email, format: { with: Devise.email_regexp }
validates :password, presence: true
validates :password, confirmation: true
validates :password, length: { in: Devise.password_length }

So what do you think about this? Is this helpful for you?

Or is it useless? Because, instead of having similar emails in one column, why don’t you just create another table to handle it. Yeaah, is that what you think right? ;)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s