Rails 4 pgsql add_index,类型为GIN或GiST

Bil*_*ill 32 postgresql ruby-on-rails ruby-on-rails-4

在Rails中可以这样做:

add_index :table, :column_name, :using => 'btree'

是否可以在带有PGSQL的Rails 4中添加GINGiST索引如下:

add_index :students, :name, :using => 'gin'

或者我是否使用手动执行语句?这背后的概念是我想保留schema.rb而不是使用structure.sql

小智 42

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

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

  • 这引发了一个错误`PG :: UndefinedObject:ERROR:数据类型字符变化没有访问方法"gin"`的默认操作符类......这是在Rails 4.2上. (10认同)
  • @King'oriMaina 在 Rails 5 中,您可以使用 `opclass ` 参数来使用默认运算符类并避免该错误:`add_index :products, :data, using: :gin, opclass: :gin_trgm_ops` https://api。 rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index (3认同)

Jos*_*osh 24

哇!我有一些头发变灰了.我正在使用rails 4.2并尝试运行此迁移,它给了我与上面的人相同的错误.

PG::UndefinedObject: ERROR: data type character varying has no default
Run Code Online (Sandbox Code Playgroud)

我发现你实际上仍然可以继续使用schema.rb而不必使用config/application.rb

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

我缺少的一件主要事情是安装postgres contrib模块.我假设杜松子酒和吉斯特之类的功能已经打开了.我从来没有注意到,但是schema.rb文件中显示了模块.它们像这样出现在顶部

ActiveRecord::Schema.define(version: 20151203234708) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"
  enable_extension "pg_trgm"
  enable_extension "fuzzystrmatch"
  enable_extension "btree_gin"
  enable_extension "btree_gist"
Run Code Online (Sandbox Code Playgroud)

如果您没有看到启用btree_gin,则无法使用该代码

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

您可以通过运行这样的迁移来安装任何模块.更改将反映在schema.rb中

class InstallSomeContribPackages < ActiveRecord::Migration
  def up
    execute "CREATE EXTENSION IF NOT EXISTS btree_gin;"
    execute "CREATE EXTENSION IF NOT EXISTS btree_gist;"
  end

  def down
    execute "DROP EXTENSION IF EXISTS btree_gin;"
    execute "DROP EXTENSION IF EXISTS btree_gist;"
  end
end
Run Code Online (Sandbox Code Playgroud)

这是postgres模块的列表

  • 您还可以使用迁移语法http://stackoverflow.com/questions/16611226/how-to-install-postgres-extensions-at-database-creation`enable_extension"btree_gin"在迁移中添加扩展. (8认同)