Mat*_*ski 4 ruby ruby-on-rails ruby-on-rails-4
在我的 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
Run Code Online (Sandbox Code Playgroud)
这按预期工作,但我想知道是否有任何方法可以使用 Railsbuilt_in add_index 方法执行相同操作?
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
Run Code Online (Sandbox Code Playgroud)
https://www.joshmcarthur.com/til/2019/10/15/fancy-postgres-indexes-with-activerecord.html