Skip to content

Instantly share code, notes, and snippets.

@shuber
Created April 1, 2015 07:43
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuber/e84a25971f7cb6aaaa5c to your computer and use it in GitHub Desktop.
Save shuber/e84a25971f7cb6aaaa5c to your computer and use it in GitHub Desktop.
ActiveRecord `add_index` patch for PostgreSQL JSONB GIN indexes
# This patch detects {index_columns} that match something like
# the example below, then strips the surrounding double quotes.
#
# "(settings->'example')"
#
# The resulting CREATE INDEX sql looks something like:
#
# CREATE INDEX "idx_users_on_settings_example" ON "users" USING gin ((settings->>'example'))
#
# Your {add_index} call should looks something like:
#
# add_index :users, "(settings->'example')", name: 'idx_users_on_settings_example', using: :gin
module AddIndexPatch
def add_index_options(*args)
super.tap do |options|
index_columns = 2
if options[index_columns] =~ /^"(\(\w+\-\>'\w+'\))"$/
options[index_columns] = $1
end
end
end
end
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:include, AddIndexPatch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment