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.
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:
Edit config/application.rb
to set the schema format:
class Application < Rails::Application #... config.active_record.schema_format = :sql #... end
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.
This should leave you with a db/structure.sql
file so add that to your revision control and delete db/schema.rb
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.