我按照README的指示尝试安装activerecord-postgis-adapter,但是无法创建模型实例,因为我一直收到下面提到的错误:
NoMethodError: undefined method `point' for nil:NilClass
以下是我的不同文件的样子:
Location.rb(更新的代码)
# == Schema Information
#
# Table name: locations
#
# id :integer not null, primary key
# locatable_id :integer
# locatable_type :string
# created_at :datetime not null
# updated_at :datetime not null
# coordinates :geography({:srid point, 4326
#
class Location < ActiveRecord::Base
#self.rgeo_factory_generator = RGeo::Geos.factory_generator
#set_rgeo_factory_for_column(:coordinates,
# RGeo::Geographic.spherical_factory(:srid => 4326) )
locFactory = RGeo::ActiveRecord::SpatialFactoryStore.instance.factory(:geo_type => 'point')
belongs_to :locatable,
polymorphic: true
validates :locatable, presence: true
attr_accessor :longitude, :latitude
end
Gemfile
gem 'rgeo'
gem 'rgeo-activerecord'
gem 'activerecord-postgis-adapter'
config/application.rb
require 'rails/all'
#require 'active_record/connection_adapters/postgis_adapter/railtie'
#require "#{Rails.root}/lib/rgeo"
config/database.yml
development:
<<: *default
database: geoproject-api_development
adapter: postgis
schema_search_path: "public,postgis"
在添加记录后,当我尝试检索它时,我得到以下结果:
irb(main):003:0> lala = Location.first
Location Load (1.6ms) SELECT "locations".* FROM "locations" ORDER BY "locations"."id" ASC LIMIT 1
(Object doesn't support #inspect)
irb(main):004:0> lala.class.name => "Location"
irb(main):005:0> puts lala
#<Location:0x007fdfd4bb2860>
=> nil
irb(main):006:0> puts lala.inspect
NoMethodError: undefined method point' for nil:NilClass
想知道为什么会出现这种情况,或者如何解决?更具体地说,为什么它是NilClass,并且为什么#inspect找不到?
以下是我的schema.rb
create_table "locations", force: :cascade do |t|
t.integer "locatable_id"
t.string "locatable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.geography "coordinates", limit: {:srid=>4326, :type=>"point", :geographic=>true}
end
我正在使用Rails 4.2.1版本。
config.default = RGeo::Geographic.spherical_factory(srid: 4326) end``` 一切都能正常工作。这与工厂的选择方式有关。但在我的情况下,我只需要地理工厂。所以对我来说它起作用了。
- bob