【问题标题】:Deserialize RGeo column as SphericalPointImpl将 RGeo 列反序列化为 SphericalPointImpl
【发布时间】:2016-05-18 00:54:30
【问题描述】:

在 Rails 4.2.4 和 activerecord-postgis-adapter 3.1.2 中有一个 RGeo 列的表

class CreateAddresses < ActiveRecord::Migration
  def change
    create_table :addresses do |t|
      t.st_point :coordinates,   geographic: true, srid: 4326
    end

    add_index :addresses, :coordinates, using: :gist
  end
end

以及按位置对对象进行分组的方法

def self.group_by_coords
    includes(:address).
    joins(:address).
    group('addresses.coordinates::geometry').
    pluck(
      'array_agg(realties.id) as ids, addresses.coordinates::geometry'
    )
  end

配合相应的测试:

describe 'group_by_coords' do
  it 'correctly group realties' do
    # create samples
    expect(Realty.group_by_coords).to eq(
      [[[r1.id, r2.id], r1.address.coordinates], [[r3.id], r3.address.coordinates]]
    )
  end
end

问题是pluck 返回RGeo::Geos::CAPIPointImpl 而不是RGeo::Geographic::SphericalPointImpl

expected: [[[1670, 1671], #<RGeo::Geographic::SphericalPointImpl:0x3fd37e9b8a20 "POINT (106.0 10.0)">], [[1672], #<RGeo::Geographic::SphericalPointImpl:0x3fd37ab2dddc "POINT (106.5 10.5)">]]
got: [[[1671, 1670], #<RGeo::Geos::CAPIPointImpl:0x3fd37a335a44 "POINT (106.0 10.0)">], [[1672], #<RGeo::Geos::CAPIPointImpl:0x3fd37a33560c "POINT (106.5 10.5)">]]

我相信为了解决这个问题,必须指定一个正确的工厂。我试过了 像这样指定它

RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
  config.default = RGeo::Geos.factory_generator
  config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point", sql_type: "geography")
end

但它会将所有点反序列化为RGeo::Geos::CAPIPointImpl,这更通用且与现有代码库不兼容。

所以问题是如何将所有点反序列化为RGeo::Geographic::SphericalPointImpl

【问题讨论】:

    标签: postgresql ruby-on-rails-4 activerecord postgis rgeo


    【解决方案1】:

    这里可能比您预期的要简单,让我们看看前几个字符。

    expected: [[[1670, 1671],...
    got: [[[1671, 1670],...
    

    为什么它们会有所不同?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多