Search code examples
ruby-on-railsrails-activerecordpostgis

Saving a point value using activerecord-postgis-adapter


I am using activerecord-postgis-adapter in my rails app and I have a column to store a point but I can't work out how to save a value for the point.

In my schema I have

  create_table "privacy_zones", force: :cascade do |t|
    t.bigint "user_id"
    t.geography "original_point", limit: {:srid=>4326, :type=>"st_point", :geographic=>true}, null: false
    t.geography "random_in_range", limit: {:srid=>4326, :type=>"st_point", :geographic=>true}, null: false
    t.integer "range", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_privacy_zones_on_user_id"
  end

and in my controller I have

def create
    @privacy_zone = PrivacyZone.new(
        range: params[:privacy_zone][:range],
        original_point: "ST_POINT(#{params[:privacy_zone][:original_point][0]}, #{params[:privacy_zone][:original_point][1]})",
        random_in_range: "ST_POINT(#{params[:privacy_zone][:random_in_range][0]}, #{params[:privacy_zone][:random_in_range][1]})",
        user: current_user
    )

    p @privacy_zone
end

When I post to it I see this in the server log

Started POST "/profile/privacy_zone" for 127.0.0.1 at 2019-03-02 16:47:24 +1030
Processing by PrivacyZoneController#create as HTML
  Parameters: {"privacy_zone"=>{"original_point"=>[35.87006446264988, 107.75390625], "random_in_range"=>[35.87185877011052, 107.75633485018554], "range"=>400}}
  User Load (4.4ms)  SELECT  "users".* FROM "users" WHERE "users"."uid" = $1 LIMIT $2  [["uid", "test@example.com"], ["LIMIT", 1]]
#<PrivacyZone id: nil, user_id: 1, original_point: nil, random_in_range: nil, range: 400, created_at: nil, updated_at: nil>

original_point and random_in_range are nil so the record will not save. What is the proper way to insert data to st_point columns?


Solution

  • My code was generating values in the form ST_POINT(42.14603262169405, 69.43359375000001)

    The correct value is POINT(42.14603262169405 69.43359375000001) (Without the ST_ and without ,)