タケユー・ウェブ日報

Ruby on Rails や Flutter といったWeb・モバイルアプリ技術を武器にお客様のビジネス立ち上げを支援する、タケユー・ウェブ株式会社の技術ブログです。

Rails + PostGIS (activerecord-postgis-adapter) で矩形内に含まれるレコードを検索する

# == 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)

postgis.net

blog.takeyuweb.co.jp