ruby-on-rails - 指定 RGeo-ActiveRecord 列的点类型

标签 ruby-on-rails activerecord postgis rgeo

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)">

我正在使用最新的'activerecord-postgis-adapter 3.1.4'rails 4.2.4

也许有人知道如何解决这个问题,即使坐标始终返回RGeo::Geographic::SphericalPointImpl的实例?

最佳答案

当您选择带有 addresses.coordinates::geometry 的列时,您将强制 Postgres 返回几何类型的列。当您执行 Realty.last.address.cooperatives 操作时,您将返回不同的 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")
end

关于ruby-on-rails - 指定 RGeo-ActiveRecord 列的点类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35428447/

相关文章:

ruby-on-rails - 为什么在 Rails 3 的 View 中可以识别非英语字符串,但在助手中却不能识别?

ruby-on-rails - ActiveRecord 将 Rails 应用程序从 Sqlite 转换为 PostgreSQL 时出错

database - 如何更改安装 postgis 的位置?后置数据库

ruby-on-rails - 从 "rspec spec"和 rspec "spec/services/my/module"运行 rspec 时模块的差异

mysql - 我可以查询具有符合特定条件的多个关联记录的记录吗?

ruby-on-rails - Mongoid 不在查询中

ruby-on-rails - 如何避免ActiveRecord模型双重保存?

mysql - ActiveRecord 深层嵌套查询和计算列

PostgreSQL:如何解决 ST_Intersects 中的 "Could not generate outside point"错误

sql - Postgres - 使用 PostGis 在 LINQ 或 SQL 中进行地理空间搜索