Rails和Postgres Hstore:你能在迁移中添加索引吗?

我有一个迁移,我创建了一个像这样的产品表

class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.hstore :data t.timestamps end end end 

在activerecord-postgres-hstore页面上,他们为表添加一个索引(在SQL中)

 CREATE INDEX products_gin_data ON products USING GIN(data); 

然而,迁移不会跟踪这种变化(我猜是因为它是Postgres特定的?),有没有办法从迁移中创建索引?

谢谢!

是! 您可以进行另一次迁移并使用’execute’方法……如下所示:

 class IndexProductsGinData < ActiveRecord::Migration def up execute "CREATE INDEX products_gin_data ON products USING GIN(data)" end def down execute "DROP INDEX products_gin_data" end end 

更新:您可能还想在config / application.rb中指定此行:

 config.active_record.schema_format = :sql 

你可以在这里阅读: http : //apidock.com/rails/ActiveRecord/Base/schema_format/class

在Rails 4中,您现在可以在迁移中执行以下操作:

  add_index :products, :data, using: :gin