Mr94
Mr94

Reputation: 143

Case insensitive active record query in rails-4

Currently I am working on a project in rails 4 in which I have a user-page at example.com/username but it only finds the record if i use username in proper case, how can I perform case insensitive search in active record rails. Check out my code below

@user = User.find_by_username(params[:username].downcase)

Upvotes: 4

Views: 2383

Answers (3)

rodsoars
rodsoars

Reputation: 401

You can use Arel Tables.

# Suppose the target username in DB is 'FooBAR'.
t = User.arel_table
@user = User.find_by(t[:username].matches 'foobar')

This will find users with usernames like 'FooBar', 'foobar', 'FOOBAR' and so on.

More details here: https://github.com/rails/arel.

Upvotes: 0

Brent
Brent

Reputation: 101

Another option could be:

def self.search(query)
    where("lower(name) LIKE lower(?)", "%#{query}%") 
end

This would work in sqlite or in PostgreSQL.

Upvotes: 1

phoet
phoet

Reputation: 18845

you will have to use something similar to where("username ILIKE ?"). the ILIKE or similar syntax is dependant on your database though.

Upvotes: 3

Related Questions