Rails和Postgres Hstore:你能在迁移中添加索引吗? [英] Rails and Postgres Hstore: Can you add an index in a migration?

查看:137
本文介绍了Rails和Postgres Hstore:你能在迁移中添加索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a migration where I create a products table like so

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中)

On the activerecord-postgres-hstore page they add an index to the table (in SQL) with

CREATE INDEX products_gin_data ON products USING GIN(data);

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

However that change is not tracked by migrations (I'm guessing because it's Postgres specific?), is there a way to create an index from within a migration?

谢谢!

推荐答案

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

Yes! You can make another migration and use the 'execute' method... like so:

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中指定此行:

UPDATE: You might also want to specify this line in config/application.rb:

config.active_record.schema_format = :sql

您可以在此处阅读: http://apidock.com/rails/ActiveRecord/Base/schema_format/class

这篇关于Rails和Postgres Hstore:你能在迁移中添加索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆