Module: Locatable::MigrationHelpers

Defined in:
lib/locatable/migration_helpers.rb

Instance Method Summary collapse

Instance Method Details

#make_locatable(table, latitude:, longitude:) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/locatable/migration_helpers.rb', line 2

def make_locatable(table, latitude:, longitude:)
  reversible do |dir|
    dir.up do
      execute <<~SQL
        ALTER TABLE #{table}
        ADD COLUMN location_geography geography(Point, 4326)
        GENERATED ALWAYS AS (
          ST_Point(#{longitude}, #{latitude}, 4326)::geography
        ) STORED,
        ADD COLUMN location_geometry geometry(Point, 4326)
        GENERATED ALWAYS AS (
          ST_Point(#{longitude}, #{latitude}, 4326)
        ) STORED;
      SQL
    end

    dir.down do
      remove_column table, :location_geometry
      remove_column table, :location_geography
    end
  end

  add_index table, :location_geography, using: :gist
  add_index table, :location_geometry, using: :gist
end