2

How could I create an index like this

CREATE INDEX index_companies_on_addresses_on_zipcode ON companies USING gin ((addresses -> 'zipcode'));

using the syntax of migrations?

I've created using the syntax below and it was created on database

execute "CREATE INDEX index_companies_on_addresses_on_zipcode ON companies USING gin ((addresses -> 'zipcode'));"

but when I saw schema.rb index wasn't there.

I've tried

add_index :companies, :addresses, using: :gin

but it create an index only on column addresses(is a jsonb) not on key zipcode.

1 Answer 1

2

AFAIK there's no way to make add_index understand that sort of indexing. Fear not, there are ways around this. You're using jsonb so there's no need to worry about database portability so you can switch from db/schema.rb to db/structure.sql for managing your schema. The db/structure.sql file is pretty much a native SQL dump of your database structure so it will contain everything that the database understands (CHECK constraints, advanced indexes, ...).

The process is quite simple:

  1. Edit config/application.rb to set the schema format:

    class Application < Rails::Application
      #...
      config.active_record.schema_format = :sql
      #...
    end
    
  2. Run your migration that uses execute as normal. You'll want to use separate up and down methods in your migrations or reversible inside the usual change method because ActiveRecord won't know how to reverse execute some_raw_sql on its own.

  3. This should leave you with a db/structure.sql file so add that to your revision control and delete db/schema.rb.

  4. Use different rake tasks for working with structure.sql instead of schema.rb:

    • db:structure:dump instead of db:schema:dump
    • db:structure:load instead of db:schema:load
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.