5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでPostGISなカラムに値を入れる

Posted at

TL;DR

PostGIS入れてactiverecord-postgis-adapter入れてgeometry型カラムを持つモデル作ったけどRailsでどうやって値入れるんだっけ?
→これでいけそう。

RGeo::Geographic.spherical_factory(srid: 4326).point(139.7003912, 35.6897376)

環境

mac OS X mojave
Ruby on Rails 5.2.3

検証

  • PostgreSQLをインストール(PostGISも)
$ brew install postgresql
$ brew install postgis
$ brew services postgresql start
  • Railsプロジェクトを立ち上げ、 activerecord-postgis-adapter gemを追加
$ rails new test_application
$ cd test_application
$ echo "gem 'activerecord-postgis-adapter'" >> Gemfile
$ bin/bundle
  • DBを初期化
$ bin/rails db:create
$ bin/rails db:gis:setup
  • モデルを作成
$ bin/rails g model Location name:string point:geometry #geometry型でモデルを作成
$ bin/rails db:migrate
Location.create(
  name: "新宿駅",
  point: RGeo::Geographic.spherical_factory(srid: 4326).point(139.7003912, 35.6897376)
)
  • DBに値が挿入されていることを確認
$ bin/rails c
irb(main):001:0> Location.all
=> #<ActiveRecord::Relation [#<Location id: 1, name: "新宿駅", point: #<RGeo::Cartesian::PointImpl:0x3fcd7929c4e0 "POINT (139.7003912 35.68973764)">>]>
5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?