Case insensitive search in Rails [duplicate]

霸气de小男生 提交于 2019-12-05 03:56:23

问题


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.


回答1:


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




回答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])


来源:https://stackoverflow.com/questions/19303637/case-insensitive-search-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!