Rails + ActiveRecord + Postgres:如何匹配不区分大小写的子字符串?

big*_*ato 5 postgresql activerecord ruby-on-rails

我必须查找User模型中包含子串"cpg"的所有电子邮件.所以它会匹配"cpg@yahoo.com","cpg3333 @ yahoo.com"等

我很确定如何做不区分大小写(使用User.where("lower(email)...")但我不知道如何找到子字符串.

我正在使用Rails 3 + Postgres 9.x.

sev*_*cat 14

在Rails中没有任何东西可以使用PostgreSQL ilike(不区分大小写的函数).

像这样: User.where("email ilike '%cpg%'")


Tyl*_*ick 9

如果您不希望在搜索电子邮件字段时始终记得调用lower(email)(以及input.downcase在Ruby中输入),则可以email使用citext数据类型使列本身不区分大小写.

这就是我刚刚做的.我创建了这样的迁移:

class ChangeUsersEmailToCitext < ActiveRecord::Migration
  def up
    # Rails 4:
    #enable_extension("citext")
    # Rails 3:
    execute 'create extension citext'

    change_table :users do |t|
      t.change :email, :citext
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在我不再需要做任何额外的努力来使查询不区分大小写!这些都是我现在在幕后自动处理的.

这使用PostgreSQL的citext扩展.

http://www.sfcgeorge.co.uk/posts/2013/11/12/case-insensitive-usernames-with-postgres有一篇很好的文章.