我使用的是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迁移中创建这个索引的正确方法是什么?
您不能在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
Rails 5增加了对在表达式索引上指定运算符类的支持
例如:
def change
add_index :patients, 'lower(last_name) varchar_pattern_ops', name: "index_patients_on_name_unique", unique: true
end
源
您需要对代码进行一些细微的更改。将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