2014-03-06 43 views
5

我想要使用PostgreSQL中存在的点类型类型。我做:Rails移植中的PostgreSQL点类型

rails g model Test point:point 

产生的迁移:

class CreateTests < ActiveRecord::Migration 
    def change 
    create_table :tests do |t| 
     t.point :point 

     t.timestamps 
    end 
    end 
end 

当我运行:

rake db:migrate 

结果是:

== CreateTests: migrating ==================================================== 
    -- create_table(:tests) 
    rake aborted! 
    An error has occurred, this and all later migrations canceled: 

    undefined method `point' for #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x000000038991a0>/home/i/Dropbox/programming/ruby/rails_pg_for_tests/db/migrate/20140306151700_create_tests.rb:4:in `block in change' 
    /home/i/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-4.0.2/lib/active_record/connection_adapters/abstract/schema_statements.rb:184:in `create_table' 
    /home/i/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-4.0.2/lib/active_record/migration.rb:625:in `block in method_missing' 
    /home/i/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-4.0.2/lib/active_record/migration.rb:597:in `block in say_with_time' 
... 

可能我需要安装PostGIS,但我不明白什么,如果我有点键入PostgreSQL。我只需要存储经纬度而无需其他选项。

我该如何使用这种点型或在这种情况下使用哪种更好?

谢谢。

+1

仅仅因为PostgreSQL有一个点类型,并不意味着ActiveRecord的支持它。 – sevenseacat

+1

'point'类型来自PostgreSQL,与PostGIS的'geometry'类型无关。 –

回答

2

您收到迁移代码undefined method 'point' for #<ActiveRecord:...错误

t.point :point 

因为point方法ActiveRecord不存在。

ActiveRecord本身支持以下data types

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, 
:time, :date, :binary, :boolean 

见的ActiveRecord的official documentation对于相同。

正如@bridiver建议,你可以选择与t.column :point, 'point'指定其他类型比支持的ActiveRecord的数据类型(如上所列)但作为ActiveRecord文档

这不会是数据库引用不可知论的,通常应该避免。

UPDATE

我会建议使用的activerecord-postgis-adapter gem的好处,通过@euricovidal的建议。它是pgsql的地理空间扩展,它充当PostGIS查询函数的包装,并允许您编写地理感知迁移。 它将允许你创建一个point类型,并使用这个你当前的语法应该工作。例如,

参见PostGIS ActiveRecord Adapter: Creating Spatial Tables。您还需要更新database.yml文件中的adapterpostgis才能生效。

+0

请添加评论,以描述为什么你投票答案,以便我可以改进答案,不要只是投票。 –

+0

我投下了它,因为它是错的。您可以通过使用列来指定任意类型,如下所述。 – bridiver

+0

@bridiver谢谢你的提示。我在答复中添加了解释。 –

6

你可以,如果你正在使用ActiveRecord-PostGIS的适配器你需要的database.yml更改适配器的PostGIS作为一个字符串

t.column 'point', 'point' 
+2

第一个'point'是列名,第二个是列类型。 –

0

你最有可能需要修改config\database.yml引用PostGIS的作为数据库适配器

default: &default 
    adapter: postgis 
    encoding: unicode 
    pool: 5 
    timeout: 5000 
    host: localhost 

development: 
    <<: *default 
    database: learning_rails 
    username: brentpayne 
    password: 

您可能还需要编辑您的迁移到指定:pointgeographic所以你可以计算距离。

t.point :point, :geographic => true 

但是您遇到的错误是相同的地雷,当我离开了我的适配器设置为PostgreSQL的。将其更改为postgis解决了我的问题。

参考:​​