Ishu
Ishu

Reputation: 648

Saving a Point type to postgres with activerecord-postgis-adapter

I am trying to save a geographic point to a postgis enabled postgres table. The table looks like follows:

address:string
longlat: point

The rails application is using activerecord-postgis-adapter. When i try and do:

l = Location.new
l.longlat = 'POINT(28.72292 77.123434)'
l.address = "My Address"
l.save

Activerecord is throwing an error

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for type point: "0020000001000010e6403774bc6a7ef9db405347ef9db22d0e

It seems like activerecord-postgis-adapter is internally converting the point type to string before saving which should not be the case. Any help on where i am going wrong is appreciated.

Upvotes: 2

Views: 2375

Answers (1)

nathanvda
nathanvda

Reputation: 50057

the WKT format cannot be used to update a geometry directly, unless you would be using a sql statement.

The easiest way is to use Rgeo (might need to include the gem explicitly):

l = Location.new
# POINT(28.72292 77.123434)
l.longlat = RGeo::Cartesian.factory(:srid => 4326).point(28.72292, 77.123434)
l.address = "My Address"
l.save

Alternatively, if you receive the WKT format, and do not want to parse it, you could do something like

l = Location.new
l.longlat = RGeo::Cartesian.factory(:srid => 4326).parse_wkt('POINT(28.72292 77.123434)')
l.address = "My Address"
l.save

If you do not want to use rgeo, you can use your database directly:

l = Location.new
l.address = "My Address"
l.save

Location.connection.execute("update locations set longlat=St_GeomFromText('POINT(28.72292 77.123434)', 4326) where id=#{l.id}")

but this requires two queries.

Note: I assumed in both cases your srid is 4326 (wgs84), you should change this if you need another coordinate system.

Upvotes: 5

Related Questions