Skip to content

Instantly share code, notes, and snippets.

@bjonord
Created November 2, 2013 11:54
Show Gist options
  • Save bjonord/7278128 to your computer and use it in GitHub Desktop.
Save bjonord/7278128 to your computer and use it in GitHub Desktop.
earth_box in ActiveRecord
# Migration to add cube and earthdistance extensions.
class CreatePostgresExtensions < ActiveRecord::Migration
def up
ActiveRecord::Base.connection.execute("CREATE EXTENSION cube;")
ActiveRecord::Base.connection.execute("CREATE EXTENSION earthdistance;")
end
def down
ActiveRecord::Base.connection.execute("DROP EXTENSION earthdistance;")
ActiveRecord::Base.connection.execute("DROP EXTENSION cube;")
end
end
# This requires the postgres-contrib package(This is preinstalled if you installed postgres via homebrew)
# See the migration below to enable these functions.
# == Parameters:
# @lat = Float8
# @lon = Float8
# The third parameter for ll_to_earth is the radius of your selection in meters.
# == Returns:
# An Array containing the matching results.
City.where("earth_box( ll_to_earth(#{lat}, #{lon}), 5000) @> ll_to_earth(latitude, longitude)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment