# == Schema Information # # Table name: places # # id :bigint not null, primary key # geom :geography not null, point, 4326 # # Indexes # # index_places_on_geom (geom) USING gist class Place < ApplicationRecord end class CreatePlaces < ActiveRecord::Migration[6.0] def change create_table :places do |t| t.st_point :geom, geographic: true, null: false t.index :geom, using: :gist end end end
Place.where("geom && ST_MakeEnvelope(:min_lng, :min_lat, :max_lng, :max_lat, 4326)", min_lat: min_lat, min_lng: min_lng, max_lat: max_lat, max_lng: max_lng)
st_point
は activerecord-postgis-adapter による拡張geom
は座標を示すジオグラフィ型 (SRID 4326)- ST_MakeEnvelope で最小値座標と最大値座標からなる矩形ポリゴンを生成
&&
演算子で矩形ポリゴンと交差する座標を選択