Rails - 按大陆、国家和城市进行地理编码

Rails - geocode by continent, country and city

我正在尝试将世界上一些世界上最好的城市放在一起。

我有:

    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 进行地理编码。

非常感谢!

你可以这样做:

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

地理编码不需要是列,可以是实例方法

class City < ApplicationRecord

  geocoded_by :address

  def address
    [city_name, country_name].compact.join(', ')
  end

end