1

I have this method, which works great:

def find
  return User.where(:name=> params[:search])
end

My problem is that it is case sensitive, so if I search for "bob", it will not return any users whose name is capitalized (e.g. "Bob"). Is there a way to make it case insensitive?

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
user2472480
  • 125
  • 1
  • 10
  • check out [this post](http://stackoverflow.com/questions/2220423/case-insensitive-search-in-rails-model) – mdemolin Jan 02 '14 at 11:09

3 Answers3

3

You can also use

User.where('name ILIKE ?', params[:search])
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
Rashmi Nair
  • 329
  • 2
  • 5
1

This should do it:

def find
  User.where("lower(name) = ?", params[:search].downcase)
end

By making the db entry lowercase and the search params lowercase, then case insensitivity is no longer an issue.

Also, the return statement is not needed in Ruby since we have implicit return statements.

How does it work?

You can pass raw SQL in to the .where command. lower() is a function in SQL, not Ruby, which will return the single string parameter as a lowercase string. It's the equivilent of .downcase in Ruby. Now that both the original string and the string to compare are lowercase, the case no longer matters.

Max Woolf
  • 3,988
  • 1
  • 26
  • 39
  • If your table is big, this method is extremely slow. It runs the lower method for all the rows in your table. – Michael Koper Jan 02 '14 at 11:29
  • @MichaelKoper If you have a text/varchar column and know that you'll need to perform fast case-insensitive searches on it, you can (and should!) create an index on the function result. Here's an example for PostgreSQL: CREATE INDEX test1_lower_col1_idx ON test1 (lower(col1)); – mercurial May 13 '16 at 15:17
-1

Something like this:

def find
    return User.where(:name=> params[:search].downcase)
end
zrl3dx
  • 7,699
  • 3
  • 25
  • 35