Case insensitive search in Rails

16,103

Solution 1

Yes, Rails supports case-insensitive queries via the built-in Arel library or a gem such as Squeel.

Solution 2

Are there options that we can pass to the find_by helper in Rails? This would be a nice one...

No there isn't. (see the API)
Yes, that would be a nice one.

You will probably not accept this answer because your question wasn't really a question
Which is probably why you got downvoted.

Maybe you could also lowercase the params[:find] (params[:find].downcase) and care to get PG setup on your dev machines.

Category.where("LOWER(name) LIKE ?", "%#{params[:find].downcase}%").first

In the meantime, you could extract the query in your model:

category.rb

def self.search_by_name(name)
  if Rails.env.development?
    where("LOWER(name) LIKE ?", "%#{name.downcase}%").take
  else
    where("LOWER(name) ILIKE ?", "%#{name}%").take
  end       
end

controller

@tag = Category.search_by_name(params[:find])
Share:
16,103
Dudo
Author by

Dudo

I like code. It's something I picked up as a hobby, and now I'm fortunate enough to be paid for it. My primary language is Ruby, but I'm trying out Elixir and Rust... functional languages in general. I ask a lot of questions, and I try to answer just as many.

Updated on June 04, 2022

Comments

  • Dudo
    Dudo almost 2 years

    The best way I've found to search for things where I specifically don't want character-case to matter is:

    @tag = Rails.env.development? ? Category.where("LOWER(name) LIKE ?", "%#{params[:find]}%")[0] : Category.where("LOWER(name) ILIKE ?", "%#{params[:find]}%")[0]
    

    I have to have the .env finder because I use Heroku, and I haven't cared to get PostgreSQL setup on my dev machines. Still, isn't there something like:

    @tag = Category.find_by_name(params[:find], case_sensitive: false)
    

    Are there options that we can pass to the find_by helper in Rails? This would be a nice one.