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

kre*_*eek 12 migration postgresql indexing ruby-on-rails hstore

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

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

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

activerecord-postgres-hstore页面上,他们使用表格(在SQL中)添加索引

CREATE INDEX products_gin_data ON products USING GIN(data);
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

mou*_*v99 27

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

    add_index :products, :data, using: :gin
Run Code Online (Sandbox Code Playgroud)


agr*_*ann 15

是! 你可以进行另一次迁移并使用'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
Run Code Online (Sandbox Code Playgroud)

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

config.active_record.schema_format = :sql
Run Code Online (Sandbox Code Playgroud)

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

  • 另外你可能想要它:CREATE INDEX CONCURRENTLY products_gin_data ON产品使用GIN(数据)这将允许它在添加索引时不锁定表. (3认同)