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.

有帮助吗?

解决方案 2

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

其他提示

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])
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top