最好使用 Geocoder Gem https://github.com/alexreisner/geocoder
实际上,在您的模型 shop.rb 中,您需要添加以下内容,以确保每次用户更新您视图中的地址时,您的商店表中的经度和纬度字段都会更新。
宝石文件
gem 'geocoder', '~> 1.4'
您应该在 Shop 表中添加两个字段,经度和纬度,确保它们都是浮点数,如果您还没有这样做,请进行迁移。
假设这address
是一个字段并且它存在于您的商店表中,并假设这location.html.erb
是您商店中的一个视图,并且在该视图中您有这样的东西
<%= f.text_field :address, placeholder: "Your Shop's Address", class: "form-control", required: true, id: "shopaddress" %>
我还假设,当您创建 Shop 模型时,您添加了属性active:boolean
并user:references
知道商店是否处于活动状态,并且知道商店属于哪个用户。所以一个用户有很多商店。
ID shopaddress,我在这里包括以防您想将 Geocomplete gem 与 Google Maps API 与 Places Library 一起使用。但是你不需要它。
在商店.rb
geocoded_by :address
# Will Update if changed
after_validation :geocode, if: :address_changed?
当然,在您的控制器中,您需要确保首先授权更新地址的人,然后运行这些方法。因此,不必重复自己。您可能想在您的商店控制器中创建类似的东西。
在shop_controller.rb 中
class ShopsController < ApplicationController
# If your shop owners are creating many shops you will want to add
#your methods here as well with index. Eg. :create, :new
# In case you have a view shop page to show all people
before_action :set_shop, except: [:index]
before_action :authenticate_user!, except: [:show]
# I am assuming that you also want to update other fields in your
#shop and the address isn't the only one.
before_action :is_user_authorised, only: [:name_x, :name_y, :name_z, :location, :update]
def index
@shops = current_user.shops
end
def show
@photos = @shop.photos
@product_reviews = @shop.product_reviews
end
def name_x
end
def name_y
end
def name_z
end
def location
end
def update
new_params = shop_params
# To ensure the shop is actually published
new_params = shop_params.merge(active: true) if is_shop_ready
if @shop.update(new_params)
flash[:notice] = "Saved..."
else
flash[:alert] = "Oh oh hmm! something went wrong..."
end
redirect_back(fallback_location: request.referer)
end
private
def set_shop
@shop = Shop.find(params[:id])
end
def is_user_authorised
redirect_to root_path, alert: "You don't have permission" unless
current_user.id == @shop.user_id
end
# You can play with this here, what defines a ready shop?
def is_shop_ready
!@shop.active && !@shop.name_x.blank? &&
!@shop.name_y.blank? && !@shop.name_z.blank? &&
!@shop.address.blank?
end
# Here you are allowing the authorized user to require her shop and it's properties, so that she can update them with update method above.
# eg_summary, eg_shop_type, eg_shop_name are just additional #example properties that could have been added when you iniitially created your Shop model
def shop_params
params.require(:shop).permit(:address, :active, :eg_shop_name, :eg_shop_summary, :eg_shop_type)
end
end