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

12
我有一个迁移,我会像这样创建一个产品表。
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的?),有没有一种方法可以在迁移中创建索引?

谢谢!

2个回答

28
在Rails 4中,您现在可以在迁移中执行以下操作:
    add_index :products, :data, using: :gin

这不会生成GIN(数据)。可能是生成器中的错误。 - millisami
1
Rails 4.0.2 给了我这个在 structure.sql 中的代码: CREATE INDEX index_products_on_data ON products USING gin (data); - mountriv99

16

是的!你可以创建另一个迁移并使用 '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


太好了,感谢您提供有关config.active_record.schema_format的提示。 - kreek
3
另外你可能想这样做:CREATE INDEX CONCURRENTLY products_gin_data ON products USING GIN(data),这样可以在添加索引时避免锁定表。 - CraigKerstiens
你也可以在 DROP 上使用 CONCURRENTLY。 - Cymen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接