在 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
?