Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails and Postgres Hstore: Can you add an index in a migration?

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

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

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?

thanks!

like image 386
kreek Avatar asked May 14 '12 23:05

kreek


People also ask

What is index true in rails migration?

index: true vs foreign_key:true in migration When we write index: true to any column, it adds a database index to this column. Foreign key enforce referential integrity. In the example above we have profile_id column in educations table which is foreign key of profiles table.

What is hstore in Rails?

One of these column types is called hstore, a column based on a key-value data structure. This feature is extremely useful when you have a data structure that can vary, but that needs to be queried eventually. In Rails you can use serialized attributes, but this approach has a problem: you can't query the stored value.

What is Add_index in rails migration?

add_index(table_name, column_name, options = {}) public. Adds a new index to the table. column_name can be a single Symbol, or an Array of Symbols. The index will be named after the table and the column name(s), unless you pass :name as an option.


2 Answers

In Rails 4, you can now do something like this in a migration:

    add_index :products, :data, using: :gin
like image 97
mountriv99 Avatar answered Oct 17 '22 18:10

mountriv99


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

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

config.active_record.schema_format = :sql

You can read about it here: http://apidock.com/rails/ActiveRecord/Base/schema_format/class

like image 44
agronemann Avatar answered Oct 17 '22 17:10

agronemann