如何在Rails迁移中创建此特定的PostGres索引?

时间:2016-10-12 19:04:49

标签: ruby-on-rails postgresql indexing migration gin

我正在使用Rails 4.2.7和PostGres 9.5。我正在尝试在我的表上创建一个trqm索引(以便于LIKE搜索),所以我创建了这个迁移

class AddTrqmIndexOnRaceTimes < ActiveRecord::Migration
  def change
    CREATE INDEX my_object_times_name_gin_trgm_idx ON my_object_times USING gin (name gin_trgm_ops);
  end
end

当我运行“rake db:migrate”...

时,会出现以下错误
StandardError: An error has occurred, this and all later migrations canceled:

undefined local variable or method `gin_trgm_ops' for #<AddTrqmIndexOnRaceTimes:0x007fdc34b40600>
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:664:in `block in method_missing'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'
/Users/mikeb/Documents/workspace/runtrax/db/migrate/20161012185951_add_trqm_index_on_my_object_times.rb:3:in `change'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'

在Rails迁移中创建此索引的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

您无法直接在ruby方法change中添加SQL。使用add_index方法,或者如果您需要超出帮助程序的功能,请使用ActiveRecord执行您的查询,如下所示:

class AddTrqmIndexOnRaceTimes < ActiveRecord::Migration
  def change
    MyObjectTime.connection.execute("CREATE INDEX my_object_times_name_gin_trgm_idx ON my_object_times USING gin (name gin_trgm_ops);")
  end
end

答案 1 :(得分:0)

Rails 5 添加了对在表达式索引上指定操作符类的支持

例如:

def change
  add_index :patients, 'lower(last_name) varchar_pattern_ops', name: "index_patients_on_name_unique", unique: true
end

source

答案 2 :(得分:0)

您需要对您的代码稍作更改。将 sql 查询包裹在 execute 中。

class AddTrqmIndexOnRaceTimes < ActiveRecord::Migration
  def change
    execute "CREATE INDEX my_object_times_name_gin_trgm_idx ON my_object_times USING gin (name gin_trgm_ops);"
  end
end