使用 activerecord-postgis-adapter ,如何从数据库查询的结果中解析/编码wkt?
我有一个简单的地方模型:
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
我按照以下方式获得所有地方:
class PlacesController < ApplicationController
def index
@places = Place.all
render json: @places.to_json
end
end
但我的JSON响应包含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"
}
]
我可以映射@places并编码这样的坐标:
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
然后我得到我想要的东西 - 以GeoJSON形式编码/解析的坐标:
[
{
"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"
}
]
编码POINT是正确的方法吗?