简体   繁体   English

不具有区分大小写的搜索活动记录

[英]Not case sensitive search with active record

I use rails 3.0.4 我使用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? 这是我的rails应用程序中的一段Arel查询,如何使用upcase方法以数据库无关的方式进行无区分大小写的搜索?

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

Thanks 谢谢

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. 首先, LIKE已经不区分大小写了,但是对于Postgres,你必须使用ILIKE来使你的搜索不区分大小写。

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: 其次,如果要使用不区分大小写与非模式匹配比较(如<>,=,<=等)进行比较,则可以使用COLLATE命令强制不区分大小写的匹配:

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 . 似乎Postgres还没有COLLATE命令,但你可以在这里查看更多关于不区分大小写的搜索选项。 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. 如果你确实需要支持多个数据库系统,那么你最好的选择是简单地创建两个不同的查询 - 一个在MySQL上运行,另一个在Postgres上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM