Case-insensitive unique index in Rails/ActiveRecord?

前端 未结 8 1636
天命终不由人
天命终不由人 2020-12-09 03:38

I need to create a case-insensitive index on a column in rails. I did this via SQL:

execute(
   \"CREATE UNIQUE INDEX index_users_on_lower_email_index 
    O         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 04:09

    I would simplify this...

    In your model:

    before_validation :downcase_email
    
    def downcase_email
      self.email = email.downcase
    end
    

    That way, the index is database agnostic, and your emails are all lowercase in the database.

提交回复
热议问题