在我的Ruby on Rails项目中,我进行了迁移,为字符串列创建了不区分大小写的索引。
class AddCeCodeToUsers < ActiveRecord::Migration
def change
add_column :users, :ce_code, :string
execute <<-SQL
CREATE UNIQUE INDEX index_users_on_lower_ce_code_index
ON users USING btree (lower(ce_code));
SQL
end
end
这可以按预期工作但我想知道有没有办法使用rails built_in add_index方法做同样的事情?
答案 0 :(得分:2)
对于mysql尝试:
add_index "users", "lower(ce_code)", name: "index_users_on_lower_ce_code"
对于PG尝试:
安装gem "schema_plus_pg_indexes"
t.index expression: "lower(ce_code)", name: "index_users_on_lower_ce_code"
答案 1 :(得分:1)
ActiveRecord 5.2 或更高版本支持在 lower(field)
上建立索引:
class AddEmailInsensitiveIndex < ActiveRecord::Migration[5.2]
def change
change_table :users do |t|
t.index "lower(email)", name: "index_users_on_lower_case_email"
end
end
end
https://www.joshmcarthur.com/til/2019/10/15/fancy-postgres-indexes-with-activerecord.html