我已经导入了一个包含 10,000 个位置的 .csv 文件,我需要遍历数据库和 geocode_by 几个字段而不是通常的“geocode_by :address”
我正在使用地理编码器 gem。
我的数据库方案是这样的
create_table "locations", :force => true do |t|
t.string "Address"
t.string "City"
t.string "State"
t.string "Zip"
t.float "latitude"
t.float "longitude"
t.datetime "created_at"
t.datetime "updated_at"
end
我可以在 Controller 操作中而不是在验证时执行此操作吗? 我应该这样做吗:
def index
@locations = Location.all
@locations.each do |l|
new_address = "#{l.Address} #{l.City} #{l.State}"
geocode_by = :new_address
end
end
但是,是的,非常感谢任何帮助,谢谢!
最佳答案
我能够使用这个 Controller 代码来工作:
def index
if params[:search].present?
@locations = Location.near(params[:search], 20, :order => :distance)
else
@locations = Location.all
@locations.each do |l|
if l.latitude.nil?
new_location = "#{l.HP_Address_1} #{l.HP_City} #{l.HP_State}"
s = Geocoder.search(new_location)
l.latitude = s[0].latitude
l.longitude = s[0].longitude
l.save
end
end
end
end
它遍历数据库中的每个条目,如果纬度和经度值尚未编码,它会调用正确的地理编码器函数,并将返回的纬度/经度值存储在数据库中。
我的数据库中有 9k 个条目,因此由于 google maps api 的限制,我每天只能编码 2k。但是对于习惯于在模型中使用 geocoded_by
创建过程中编码条目的人来说,这将适用于 Controller 。
关于ruby-on-rails - Rails GeoCoder,循环遍历现有数据库和 geocode_by :address, :city, :state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9214243/