我正在努力整理世界上一些世界上最好的城市的目录。
我有:
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
我正在使用地理编码器宝石。我该如何对此进行地理编码?城市需要由country_name
和city_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
地理编码不需要是列,它可以是实例方法
class City < ApplicationRecord
geocoded_by :address
def address
[city_name, country_name].compact.join(', ')
end
end