I'm trying to implement geocoder in my app. I would want to show Nearby places on the page of each place. I keep getting this error:
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'
I think this has to do with some places being geocoded and others not. For instance, for this address that I have, in the console, the latitude and longitude values output nil, and the .geocode method doesn't work on it. However, for other addresses, the latitude and longitude values are automatically generated (as expected). Here is the code I have:
place Model:
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
Places controller:
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
Places show view:
%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
As a result I'm only ablate create new places with some addresses while I can with others. How do I prevent this error? I was thinking maybe to have a method that checks if the location latitude and longitude have been generated. If not, then generate them before saving. How do I implement these conditionals?