GeocoderGemを使用することをお勧めしますhttps://github.com/alexreisner/geocoder
実際、モデルshop.rbでは、ユーザーがビューのアドレスを更新するたびに経度と緯度のフィールドがショップテーブルで更新されるように、以下を追加する必要があります。
Gemfile
gem 'geocoder', '~> 1.4'
Shopテーブルに経度と緯度の2つのフィールドを追加し、両方が浮動小数点であることを確認します。まだ行っていない場合は、移行を行います。
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
。つまり、1人のユーザーが多くのショップを持っています。
IDショップアドレス。プレイスライブラリでGoogleMapsAPIを使用してGeocompletegemを使用する場合に備えて、ここに含めます。しかし、そこには必要ありません。
shop.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