Using activerecord-postgis-adapter, how can I parse / encode wkt in results from database query?
I've got a simple model of Places:
class CreatePlaces < ActiveRecord::Migration[5.1]
def change
create_table :places do |t|
t.string :name
t.st_point :coords, :geographic => true
t.timestamps
end
change_table :places do |t|
t.index :coords, using: :gist
end
end
end
I get all places in following way:
class PlacesController < ApplicationController
def index
@places = Place.all
render json: @places.to_json
end
end
But my JSON in response contains WKT:
[
{
"id": 1,
"name": "test name 1",
"coords": "POINT (50.324192 19.037805)",
"created_at": "2017-09-07T20:29:19.203Z",
"updated_at": "2017-09-07T20:29:19.203Z"
}
]
I can map @places and encode coords like this:
class PlacesController < ApplicationController
def index
@places = Place.all
@places.map { |k,v| k.coords = RGeo::GeoJSON.encode(k.coords, json_parser: :json) }
render json: @places.to_json
end
end
And then I get what I wanted - encoded/parsed coords in GeoJSON form:
[
{
"id": 1,
"name": "test name 1",
"coords": {
"type": "Point",
"coordinates": [
50.324192,
19.037805
]
},
"created_at": "2017-09-07T20:29:19.203Z",
"updated_at": "2017-09-07T20:29:19.203Z"
}
]
Is it right way to encode POINT?
Add this code to one of your initializers:
RGeo::ActiveRecord::GeometryMixin.set_json_generator(:geojson)