AnApprentice
AnApprentice

Reputation: 110970

rails - Case Insensitive Search Condition

I have the following:

  @users = User.find( :all,
                      :select => 'users.*',
                      :conditions => ["fname || ' ' || lname LIKE ?", '%'+"#{params[:q]}"+'%']

Problem here is that the search input params[:q] is case sensitive. How can I make it case insensitive in my Rails 3 Heroku app?

Thanks

Upvotes: 0

Views: 2041

Answers (3)

digitalWestie
digitalWestie

Reputation: 2797

Alternatively... stick this in your model and call by passing in a string array

def self.find_all_by_lowercasing_name(str_array)
    wrapped = str_array.collect { |a| "'"+ "#{a.downcase}" + "'" }
    return MyModel.where("lower(\"my_models\".\"name\") IN (#{wrapped.join(', ')})")
end

The above works with Postgres and Sqlite

Upvotes: 0

gertas
gertas

Reputation: 17145

For PostgreSQL to get case insensitive LIKE just use ILIKE. It works according to the active locale.

Upvotes: 7

polarblau
polarblau

Reputation: 17734

A fairly "common" workaround for this problem seems to be to use the UPPER function to convert in your case "fname" or "lname" into uppercase and convert params[:q] as well, using e.g. upcase.

Upvotes: 3

Related Questions