我正在尝试在我的应用中实现地址解析器。我想在每个地方的页面上显示附近的地方。我不断收到此错误:
ActionView::Template::Error (undefined method `each' for nil:NilClass):
38:
39: %h4 Nearby places
40: - @place.nearbys.each do |place|
41: %li
42: = link_to place.name, place
43: (#{place.distance.round(2)} kilometers)
app/views/places/show.html.haml:40:in `_app_views_places_show_html_haml__1604860997730316275_70230188982160'
我认为这与某些地方进行了地理编码有关,而其他地方则没有。例如,对于我在控制台中拥有的该地址,纬度和经度值输出nil
,而.geocode
方法对此不起作用。但是,对于其他地址,纬度和经度值是自动生成的(按预期方式)。这是我的代码:
放置型号:
class Place < ApplicationRecord
geocoded_by :full_address
after_validation :geocode, if: :address_changed?
def full_address
[address1, address2, city, region].compact.join(", ")
end
def address_changed?
address1_changed? || address2_changed? || city_changed? || region_changed?
end
end
位置控制器:
def show
@place = Place.find(params[:id])
end
def create
@place = Place.new(place_params)
respond_to do |format|
if @place.save
format.html { redirect_to @place, notice: 'Place was successfully created.' }
format.json { render :show, status: :created, location: @place }
else
format.html { render :new }
format.json { render json: @place.errors, status: :unprocessable_entity }
end
end
end
地点显示视图:
%p= @place.address1
%p= @place.address2
%p= @place.city
%p= @place.region
%p= @place.phone
%p= @place.email
#mapid
%h4 Nearby places
- @place.nearbys.each do |place|
%li
= link_to place.name, place
(#{place.distance.round(2)} kilometers)
def place_params
params.require(:place).permit(:name, :description, :address1, :address2, :city, :region, :phone, :email)
end
因此,我只能烧蚀使用一些地址创建新地点,而我可以使用其他地址。如何防止此错误?我在想也许有一种方法可以检查位置纬度和经度是否已生成。如果不是,则在保存之前生成它们。如何实现这些条件?
答案 0 :(得分:2)
您可以在此处进行简单的验证,例如
if @place.nearbys.present?
- @place.nearbys.each do |place|
%li
= link_to place.name, place
(#{place.distance.round(2)} kilometers)
...