I have a Rails 6.1.4.1 app using Postgis database (Docker image: postgis/postgis:13-3.1-alpine).
I try to save geographic points in the attribute lonlat of my Branch model.
ANY attempt to save my POINT() ends up in a nil entry in the column of the branch table.
What else do I have to configure, to save POINTs in my lonlat column?
❯ which geos-config
/usr/local/bin/geos-config
❯ sudo find / -name 'libgeos*'
Password:
/usr/local/lib/libgeos_c.dylib
/usr/local/lib/libgeos.a
/usr/local/lib/libgeos.3.10.2.dylib
/usr/local/lib/libgeos_c.1.dylib
/usr/local/lib/libgeos.dylib
/usr/local/lib/libgeos_c.1.16.0.dylib
/usr/local/lib/libgeos_c.a
/usr/local/Cellar/geos/3.10.2/lib/libgeos_c.dylib
/usr/local/Cellar/geos/3.10.2/lib/libgeos.a
/usr/local/Cellar/geos/3.10.2/lib/libgeos.3.10.2.dylib
/usr/local/Cellar/geos/3.10.2/lib/libgeos_c.1.dylib
/usr/local/Cellar/geos/3.10.2/lib/libgeos.dylib
/usr/local/Cellar/geos/3.10.2/lib/libgeos_c.1.16.0.dylib
/usr/local/Cellar/geos/3.10.2/lib/libgeos_c.a
Gemfile
gem "rgeo"
gem 'activerecord-postgis-adapter'
Gemfile.lock
rgeo (2.3.0)
rgeo-activerecord (7.0.1)
activerecord (>= 5.0)
rgeo (>= 1.0.0)
activerecord-postgis-adapter (7.1.1)
activerecord (~> 6.1)
rgeo-activerecord (~> 7.0.0)
database.yml
default: &default
adapter: postgis
encoding: unicode
schema_search_path: public, postgis
schema.rb
ActiveRecord::Schema.define(version: 2022_02_14_175601) do
# These are extensions that must be enabled in order to support this database
enable_extension "fuzzystrmatch"
enable_extension "plpgsql"
enable_extension "postgis"
enable_extension "postgis_tiger_geocoder"
enable_extension "postgis_topology"
create_table "branches", force: :cascade do |t|
t.geography "lonlat", limit: {:srid=>4326, :type=>"st_point", :geographic=>true}
t.index ["lonlat"], name: "index_branches_on_lonlat", using: :gist
end
end
/initializers/rgeo.rb
config.default = RGeo::Geographic.spherical_factory(srid: 4326)
config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point")
end
models/branch.rb
class Branch < ApplicationRecord
attr_reader :lonlat
end
rails console
>> require "rgeo"
=> false
>> RGeo::Geos.supported?
=> true
branch = Branch.new
branch.lonlat = "POINT(12, 12)"
branch.save
=> true
Branch.last
=> Branch Load (1.7ms) SELECT "branches".* FROM "branches" ORDER BY "branches"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Branch id: 15 lonlat: nil>
branch2 = Branch.new
branch2.lonlat = RRGeo::Cartesian.factory(:srid => 4326).point(12, 12)
branch2.save
=> true
Branch.last
=> Branch Load (1.7ms) SELECT "branches".* FROM "branches" ORDER BY "branches"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Branch id: 16 lonlat: nil>
The issue relies in the
attr_reader :lonlatThis prevents ActiveRecord to save the value ofbranch.lonlat