当Address模型具有RGeo属性时,有一个典型的模式:
t.st_point :coordinates, geographic: true, srid: 4326通常,它被包装在RGeo::Geographic::SphericalPointImpl类中
Realty.last.address.coordinates
#<RGeo::Geographic::SphericalPointImpl:0x2b1a364b429c "POINT (106.5 10.5)">但在某些情况下,它被完全不合适的笛卡尔包装器RGeo::Cartesian::PointImpl包装
Realty.joins(:address).select('realties.id, addresses.coordinates::geometry').first.coordinates
#<RGeo::Cartesian::PointImpl:0x2b1a364a691c "POINT (106.0 10.0)">我在rails 4.2.4中使用最新的'activerecord-postgis-adapter 3.1.4'
也许有人知道如何解决这个问题,比如让coordinates总是返回RGeo::Geographic::SphericalPointImpl的实例
发布于 2016-03-11 02:19:20
当您使用addresses.coordinates::geometry选择列时,将强制Postgres返回类型为geometry的列。当您执行Realty.last.address.coordinates时,您将返回一个不同的SQL类型(点)。
我会从你的SQL查询中删除::geometry。
来自https://github.com/rgeo/rgeo-activerecord#spatial-factories-for-columns的文档
activerecord-postgis-adapter使用SpatialFactoryStore类作为查找类型的注册表,将SQL类型转换为ruby类型。
在SpatialFactoryStore单例类中注册空间工厂。ActiveRecord模型中的每个空间类型都将使用SpatialFactoryStore来检索与其类型属性相匹配的工厂。例如,可以为点类型、匹配特定SRID的类型、具有Z坐标的类型或属性的任意组合设置不同的空间工厂。
注册空间类型时支持的键及其默认值和其他允许值如下所示:
geo_type: "geometry", # point, polygon, line_string, geometry_collection,
# multi_line_string, multi_point, multi_polygon
has_m: false, # true
has_z: false, # true
sql_type: "geometry", # geography
srid: 0, # (any valid SRID)对于地理类型,默认工厂为RGeo::Geographic.spherical_factory,对于几何类型,默认工厂为RGeo::Cartesian.preferred_factory。
下面是一个设置示例:
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")
endhttps://stackoverflow.com/questions/35428447
复制相似问题