使用PostGIS的Rails

23t*_*tux 10 ruby postgresql postgis ruby-on-rails ruby-on-rails-3

首先,我使用Rails3和Ruby 1.9.2.

使用PostgreSQL和PostGIS时遇到问题.我试过两个宝石:

问题是,nofxx中的第一个工作正常,但它不提供rake任务,因此postgis.sql和spatial_ref_sys.sql被插入到数据库中.我需要这个,因为它使用测试是舒适和必要的(自动创建数据库,插入postgis sql并在运行"rake test"时执行迁移).奇怪的是,在github的README中,作者写了一些关于PostGIS助手和rake任务的东西.但他们没有实施(或者我是盲目的).

上面列出的第二个宝石为rake提供了完美的功能!但我遇到了一个我无法解决的问题.我按照自述文件中的说明进行操作,但每当我尝试在空间列上设置位置时,我都会得到以下输出:

ruby-1.9.2-p136 :010 > v = Venue.new :location => "POINT(102.0, 47.2)"
=> #<Venue id: nil, last_updated: nil, created_at: nil, updated_at: nil, location: nil>
ruby-1.9.2-p136 :011 > v.location
=> nil 
Run Code Online (Sandbox Code Playgroud)

如您所见,我使用WKT(众所周知的文本)设置了一个位置,但它始终为零.我也尝试将它保存到数据库中,但它也没有.我想通了,当我尝试使用RGeo提供的对象时

RGeo::Geos.factory.point(-122, 47)
Run Code Online (Sandbox Code Playgroud)

它说,工厂是零.因此,通过创建RGeo提供的工厂肯定存在问题.正如activerecord-postgis-adapter的README中所提到的,我在Venue模型中使用了以下行来提供这种支持:

self.rgeo_factory_generator = RGeo::Geos.factory_generator
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

因此,要找到解决方案,有两种方法:找到一种方法将rake任务放入nofxx的georuby gem中,或者使用activerecord-postgis-adapter的工厂解决问题.

希望有人可以帮助我,谢谢!

小智 13

我花了大约4个小时用"activerecord-postgis-adapter"解决同样的问题.答案很简单:"从来没有用户加入WKT".在你的情况下它必须是 v = Venue.new :location => "POINT(102.0 47.2)"然后一切正常!


23t*_*tux 12

最后我自己解决了.我正在玩rake任务,我遇到了一些问题(比如,你不能用psql的脚本提供密码......)让我烦恼.但我发现,您可以为database.yml文件提供模板选项.所以,我刚才写道:

development:
  adapter: postgresql
  pool: 5
  encoding: unicode
  database: myDatabase
  username: root
  password: *****
  su_username: root
  su_password: *****
  port: 5432
  template: template_postgis

test:
  adapter: postgresql
  pool: 5
  encoding: unicode
  database: myDatabase_test
  username: root
  password: *****
  su_username: root
  su_password: *****
  port: 5432
  template: template_postgis

production:
  adapter: postgresql
  pool: 5
  encoding: unicode
  database: myDatabase_production
  username: root
  password: *****
  su_username: root
  su_password: *****
  port: 5432
  template: template_postgis
Run Code Online (Sandbox Code Playgroud)

现在每次我创建我的数据库(在测试期间等等)都会添加所有PostGIS内容!是啊!

  • 您可以向数据库添加"script_dir"变量,该变量将执行两个必需的sql脚本以使用postgis.在activerecord-postgis-adapter中搜索"script_dir".我用它,效果很好.无需模板. (4认同)