Search code examples
ruby-on-railsrubypostgresqlpostgisruby-on-rails-6

Facing issue in st_distance and geometry with posgis adapter


I am trying to run a query from the rails console but I get an error

1st query

Location.order( ST_Distance(
    'SRID=4326;POINT(-72.1235 42.3521)',
    'SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'
  )).first

undefined method 'ST_Distance' for main:Object

2nd query

longitude_latitude = '0101000020E61000002DB29DEFA7C651C0B81E85EB51284540'

  Location.order('acc_rank desc', ST_Distance(
    'SRID=4326;POINT(-72.1235 42.3521)'::geometry,
    longitude_latitude
  )).first

undefined method 'geometry' for "SRID=4326;POINT(-72.1235 42.3521)":String

If I try to run from Postgres console I am able to run both the queries

select  ST_Distance(
aniket_t(#     'SRID=4326;POINT(-72.1235 42.3521)'::geometry,
aniket_t(#     '0101000020E61000002DB29DEFA7C651C0B81E85EB51284540'
aniket_t(#   );
   st_distance    
------------------
 1.02017481835224
(1 row)


select ST_Distance(
aniket_t(#     'SRID=4326;POINT(-72.1235 42.3521)',
aniket_t(#     'SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'
aniket_t(#   );
     st_distance     
---------------------
 0.00150567726382822
(1 row)

For the setup of PostGIS initially I have install the gem

gem "activerecord-postgis-adapter"

But later I found few answers and I install this gem too

gem "rgeo"
gem 'rgeo-activerecord'

Not sure whether the rgeo and rgeo-activerecord gems are required to run the above query

In my database.yml I have clearly specified the adapter

default: &default
  adapter: postgis
  encoding: unicode
  pool: 10 

Also, by reading few answers on StackOverflow I have also added rgeo.rb in config/initializers/rgeo.rb

RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
  # By default, use the GEOS implementation for spatial columns.
  config.default = RGeo::Geos.factory_generator

  # But use a geographic implementation for point columns.
  config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point")
end

But nothing works for me. Any help is appreciated in running those queries from the rails console

Rails: 6.0.3.7
pg gem: 1.2.3
postges version: 10.17


Solution

  • I fix the query by adding quotes to the st_distance function. Also, "rgeo"& 'rgeo-activerecord' gems are not required

    Location.order( "ST_Distance(
        'SRID=4326;POINT(-72.1235 42.3521)',
        'SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'
      )").first