【问题标题】:Ruby on Rails + PostGIS model custom initialization and custom JSON outputRuby on Rails + PostGIS 模型自定义初始化和自定义 JSON 输出
【发布时间】:2012-09-29 14:50:53
【问题描述】:

我正在使用 PostgreSQL + PostGIS 来处理空间数据,并且我还使用这个 gem activerecord-postgis-adapter 来简化代码编写。我有这个模型

class Device < ActiveRecord::Base
  attr_accessible :location
  self.rgeo_factory_generator = RGeo::Geos.factory_generator
end

Where :location 应该是 PostGIS POINT。要创建 Device 的新实例(例如在控制器的 create 方法中),我可以这样做:

params = { location: "POINT (-26 -43)" }
@device = Device.new(params)

其中“POINT (-26 -43)”是 WKT(众所周知的文本)格式中纬度 -26 和经度 -43 的点。我希望能够隐藏此实现细节并使其可以编写:

params = { latitude: -26, longitude: -43 }
@device = Device.new(params)

也许我可以通过覆盖我的设备类中的 after_initialize 方法来实现这一点。我还能做什么?

还有一件事.. 我还需要以 JSON 格式输出这个对象。现在我得到了

{ "location": "POINT (-26 -43)" }

但是,我想要类似的东西

{ "location": { "latitude": -26, "longitude": -43 } }

对此的快速解决方案是覆盖 as_json 方法。还有其他建议吗?

谢谢。

【问题讨论】:

  • 坐标轴的顺序是 POINT(XY),因此是 POINT(经纬度)。你需要翻转这些。
  • @MikeToews 好的,我知道,但这不是问题。

标签: ruby-on-rails activerecord postgis


【解决方案1】:

您需要做的就是在 Device 类中覆盖 方法 as_json 将位置键替换为想要的键:

class Device < ActiveRecord::Base
  ...
  def as_json(options = {})
    json = super(options)
    json.merge(location_as_formatted_hash)
  end

  private

  def location_as_formatted_hash
    { location: { latitude: location.lat, longitude: location.lon } }
  end
end

有了这个,你将拥有下一个:

Device.first.to_json
{ \"location\": { \"latitude\": -26, \"longitude\": -43 } }

而不是这个:

Device.first.to_json
{ \"location\": \"POINT (-26 -43)\" }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多