【发布时间】:2020-04-10 20:33:56
【问题描述】:
我需要使用 Ruby Geocoder gem 来创建一个使用来自地址搜索查询的属性的对象。我希望从地理编码器结果中接收到的数据创建一个新位置,并创建一个具有迁移属性的新对象。我在网上搜索了资源以了解如何从结果中创建对象,但我需要知道如何从经度和纬度坐标中获取位置属性。
预期的示例搜索查询:“Wall St, NY”
=> {address: "Wall Street", city: "New York, state: "New York", country: "United States of America"
位置模型
class Location < ApplicationRecord
has_many :users
geocoded_by :address
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
end
LocationController#create
def create
@location = Location.new(location_params)
if @location.save
flash[:success] = "location added!"
redirect_to location_path(@location)
else
render 'new'
end
end
迁移
class CreateLocations < ActiveRecord::Migration[6.0]
def change
create_table :locations do |t|
t.string :address
t.string :city
t.string :state
t.string :country
t.float :longitude
t.float :latitude
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby activerecord geocoder