首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用AR/Arel重写此RGeo查询?

如何使用AR/Arel重写此RGeo查询?
EN

Stack Overflow用户
提问于 2015-11-29 05:10:17
回答 2查看 600关注 0票数 1

我有以下使用原始SQL的作用域:

代码语言:javascript
复制
class DeliveryZone < ActiveRecord::Base
  def self.contains(addressable)
    point = addressable.lonlat
    where(<<-SQL.squish)
    ST_Intersects("delivery_zones"."shape", ST_GeomFromText('#{point}'))
    SQL
  end
end

其中delivery_zones.shapegeography(Polygon,4326)pointgeography(Point,4326),用于PostgreSQL类型。

在rails控制台中,它们分别是#<RGeo::Geos::CAPIPolygonImpl>#<RGeo::Geos::CAPIPointImpl>

我想写一些更类似的东西

代码语言:javascript
复制
where(arel_table[:shape].st_intersects(point))

..。但这给了我一个错误:

RuntimeError:不支持: RGeo::Geos::CAPIPointImpl

希望有人能帮我从我的模型中获得原始SQL!另外,我是RGeo/PostGIS新手,所以请不要以为我知道自己在做什么。:D

EN

回答 2

Stack Overflow用户

发布于 2016-01-07 19:09:47

还请不要假设我知道您到底在说什么,但是我使用squeel gem来使用rgeoactiverecord-postgis-adapter编写rails风格的查询。丹尼尔·祖马( Daniel )就这个话题写了一些很棒的博客,这让我在几年前就开始了。以下是本系列的第一篇:http://daniel-azuma.com/articles/georails/part-1

据我所知,这可能会有所帮助:

代码语言:javascript
复制
class DeliveryZone < ActiveRecord::Base
  def self.contains(addressable)
    where{st_intersects(:shape, addressable)}
  end
end

注意,只有在安装了squeel时,这才有效。如果你想对它特别注意,也许你应该用它来代替:

代码语言:javascript
复制
class DeliveryZone < ActiveRecord::Base
  def self.contains(addressable)
    where{st_contains(:shape, addressable)}
  end
end

很高兴有人用rails来做地理信息系统。祝你好运

票数 0
EN

Stack Overflow用户

发布于 2016-03-16 16:43:47

您可以在不使用arelsqueel的情况下完成这一任务。

where("delivery_zones.shape && ?", addressable.lonlat.to_geometry)

一般来说,这应该是可行的:

where("point_column && ?", rgeo_object.to_geometry)

下面是一个City模型的示例,其中有一个名为coordinates的点列,它是一个st_point。我想在一个由两个角点(SE &NW)定义的边框中查询所有城市:

代码语言:javascript
复制
box = RGeo::Cartesian::BoundingBox.create_from_points(
        City.first.coordinates, City.last.coordinates)

City.where("coordinates && ?", box.to_geometry)

到底怎么回事?

代码语言:javascript
复制
> box.to_geometry.to_s
=> "POLYGON ((-90.0674 29.9627, -79.09529 29.9627, -79.09529 36.18375, -90.0674 36.18375, -90.0674 29.9627))"

> City.where("coordinates && ?", box.to_geometry).to_sql
=> "SELECT \"cities\".* FROM \"cities\" WHERE (coordinates && '0020000003000010e60000000100000005c05684504816f007403df67381d7dbf5c053c6193b3a68b2403df67381d7dbf5c053c6193b3a68b2404217851eb851ecc05684504816f007404217851eb851ecc05684504816f007403df67381d7dbf5')"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33979619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档