首页 > 解决方案 > Rails - 按大陆、国家和城市进行地理编码

问题描述

我正在尝试整理一份世界上一些世界上最好的城市的目录。

我有:

    ContinentsController < ApplicationController
      def index 
      end 

      def show 
      end 
    end

    CountriesController < ApplicationController
      def index 
      end 

      def show 
      end 
    end

    CitiesController < ApplicationController
      def index 
      end 

      def show 
      end
    end

也:

    class Continent < ApplicationRecord
      has_many :countries
      validates :continent_name, presence: true
    end

    class Country < ApplicationRecord
      belongs_to :continent 
      has_many :cities
      validates :country_name, presence: true 
      validates :continent_id, presence: true 
    end

    class City < ApplicationRecord
     belongs_to :continent 
     belongs_to :country
     validates :city_name, presence: true 
     validates :country_id, presence: true 
     validates :continent_id, presence: true
    end

我正在使用地理编码器 gem。我将如何对其进行地理编码?城市需要由两者进行地理编码country_namecity_name因为世界不同地区的城市可以共享相同的名称。一个例子是位于俄罗斯和美国的圣彼得堡。

    class City < ApplicationRecord
     geocoded_by :city_name
     after_validation :geocode, if: :city_name_changed?
    end

这在圣彼得堡的情况下不起作用,因为它只是对 . 进行地理编码city_name,而不是country_name.

提前非常感谢!

标签: ruby-on-railsrails-geocoder

解决方案


你可以这样做:

class City < ApplicationRecord
 geocoded_by :address
 after_validation :geocode, if: :city_name_changed?

 def address
   "#{city_name}, #{country_name}"
 end
end

文档显示了这一点:

def address
  [street, city, state, country].compact.join(', ')
end

https://github.com/alexreisner/geocoder#geocoding-objects


推荐阅读