Not case sensitive search with active record

依然范特西╮ 提交于 2019-12-03 13:27:23

问题


I use rails 3.0.4

here is a piece of Arel query in my rails application, How can I use the upcase method to make a none case sensitive search in a database agnostic way?

Customer.where("company_id = ? and (firstname like ? or lastname like ? or reference like ?)", current_user.company_id, "%#{params[:query]}%", "%#{params[:query]}%", "%#{params[:query]}%")

Thanks


回答1:


Here are a couple of options for you.

First, LIKE is already case-insensitive, but for Postgres you'll have to use ILIKE to make your searches case-insensitive.

Customer.where('firstname LIKE ?', "%john%").first.name
=> 'John'

Second, if you want to compare using case-insensitivity with non-pattern-matching comparisons, like <>, =, <=, etc. then you can use the COLLATE command to impose case-insensitive matches:

Customer.where('firstname COLLATE utf8_unicode_ci = ?', 'john').first.name
=> 'John'

It seems that Postgres does not have a COLLATE command yet, but you can view more about case-insensitive search options here. In general when you want to perform pattern matching or complex queries you aren't going to be able to do so in a database-agnostic way. My recommendation is to use a single database system in both development and production. This ensures that your queries will also behave the same way in both environments which should lead to fewer bugs. If you do find the need to support multiple database systems then your best option is to simply create two different queries - one to be run on MySQL and one to be run on Postgres for example.



来源:https://stackoverflow.com/questions/5052051/not-case-sensitive-search-with-active-record

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