LoginSignup
2
2

More than 5 years have passed since last update.

Rails5.1でactiverecord-mysql2spatial-adapterを使う

Last updated at Posted at 2018-05-26

map-2789052_1920.jpg

activerecord-mysql2spatial-adapterはRails + MySQLで位置情報を扱う場合に使用される事があるGemです。

https://github.com/rgeo/activerecord-mysql2spatial-adapter は、ややメンテナンスされていない印象を受けます。

Rails 5.1.6にて、使用するとこんな感じ。

$ bin/rake db:migrate
rake aborted!
NoMethodError: undefined method `attribute_types_cached_by_default' for ActiveRecord::Base:Class
Did you mean?  attribute_type_decorations

Active Record 5 · Issue #19 · rgeo/activerecord-mysql2spatial-adapter を参考に https://github.com/sebastianiorga/activerecord-mysql2spatial-adapter/tree/rails-5 を使わせて頂く。

gem 'activerecord-mysql2spatial-adapter', github: 'sebastianiorga/activerecord-mysql2spatial-adapter', branch: 'rails-5'

するとこんな感じ

$ bin/rake db:migrate
rake aborted!
NameError: uninitialized constant RGeo::ActiveRecord::DEFAULT_SPATIAL_COLUMN_CONSTRUCTORS

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

別のリポジトリのIssueですが https://github.com/stadia/activerecord-mysql2rgeo-adapter/issues/7 によると https://github.com/rgeo/rgeo-activerecord/commit/bc89717b48bfc64817cca75d1981706ed3c3af3d のように DEFAULT_SPATIAL_COLUMN_CONSTRUCTORS が削除されています。

とりあえず、動かすならばこのコードを補完してあげれば良さそうです。

config/initializers/fix_activerecord_mysql2spatial_adapter.rb
# https://github.com/rgeo/rgeo-activerecord/commit/bc89717b48bfc64817cca75d1981706ed3c3af3d
module RGeo
  module ActiveRecord
    # Some default column constructors specifications for most spatial  +    # Return a feature type module given a string type.
    # databases. Individual adapters may add to or override this list.
    DEFAULT_SPATIAL_COLUMN_CONSTRUCTORS = {
      geometry_collection: {}.freeze,
      geometry:            {}.freeze,
      line_string:         {}.freeze,
      multi_line_string:   {}.freeze,
      multi_point:         {}.freeze,
      multi_polygon:       {}.freeze,
      point:               {}.freeze,
      polygon:             {}.freeze,
      spatial:             { type: "geometry" }.freeze,
    }.freeze
  end
end

これでbin/rake db:migrateが通るようになりました。

これは一時的な対策なので、ほかの方法を検討すべきかと考えています。

2
2
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
2
2