How to Find by Rails Case in Sensitive

Find by Rails Case in Sensitive – When creating a user authentication scheme, you want your usernames to be case insensitive during creation and also during authentication. Rails makes this very easy with its built-in validators and has_secure_password, but it fails to authenticate users. We want our passwords to be case sensitive, but we only care about users entering the correct characters for their usernames, not whether they capitalize them the same way they used registration. I ran into this problem today and decided ranges were the way to go. There are many suggestions on how to be case insensitive, but in the end all you need is a simple range. Here’s how and why.

Let’s say you have a user who has registered with your service as faKeUser with pAssW0rd as the password. When they sign up, we want them to be able to type dummy users, FAKEUSER, or some other variation of these uppercase letters, as long as all the letters appear in that order. However, Rails find_by and other search methods are case sensitive. One way to handle this is in the database, but I’d like to focus on a pure code solution.

Option 1: Lowercase before saving
Don’t do this with usernames. You must assume that what the user entered as their username is what they want the username to appear as. That’s all I have to say about it.

Option 2: Modify ActiveRecord::Base
You can do it, but it’s a pain in the ass. There are easier ways.

Option 3: user .where()
We are getting warmer now. This would be my second choice if it weren’t for the ranges. But I won’t go into that either, because we can take that solution and flow to the next…

See also  Oh So Jack Fashion Male Grooming Lifestyle Tips

Option 4: Use a scope
Scopes are ideal for such cases. Instead of creating modules and fiddling with ActiveRecord::Base, we can just add a simple method to our model. So we have a user table that is not case sensitive when it is created, which means another user cannot determine the name FaKeUser if the username ‘fakeUseR’ exists. big. Now when a user is logged in, we want to be able to check for the existence of the username, regardless of the case used. So this is the range:

scope :ci_find, lambda { |attribute, value| where(“lower(#{attribute}) = ?”, value.downcase).first }

This allows us to use a case-insensitive search for each column in the user form. To use it to find a user we can do the following:

user = User.ci_find(‘username’, params[:username])

And there you have it. Basic, case-insensitive discovery tools for your models. If I start needing this in more than a couple of forms, I might consider creating modules or playing around with ActiveRecord::Base.

Leave a Comment