ruby-on-rails - 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_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
推荐阅读
- android - 如何在关闭插页式广告谷歌时添加动画?
- python - 处理数据框中的数字范围数据
- javascript - javascript动态导入类模块并获取类名
- sql - 在 SQL Server 中循环遍历 JSON 单元
- database - 在事件驱动的微服务架构中维护远程状态的最佳实践是什么?
- hibernate - JPA 休眠规范
- c# - C# 开发团队中的队列管理
- python - 如何在 PyCharm 的 venv 上自动下载已安装的 python 库的 tar.gz 包
- android - 如何使用辅助功能更改文本视图的文本或隐藏文本视图?
- php - SQLITE 按组选择并限制每组的结果