0

My code is working in console but not in App

➜  Meet-and-Eat git:(master) ✗ rails c
Running via Spring preloader in process 15789
Loading development environment (Rails 5.2.2)
2.5.3 :001 > i = ["10 Palmerston Street", "DERBY"]
 => ["10 Palmerston Street", "DERBY"]
2.5.3 :002 > result = Geocoder.search("#{i[0]}, #{i[1]}").first.coordinates
 => [52.9063415, -1.4937474]

My code :

<% @places = [] %>
<% @placesCoordinations = [] %>

<% @information.each do |i| %>
  <% @places.push([i.address1, i.town, i.postcode, information_path(i)]) %>
<% end %>

<% @places.each do |i| %>
  <% result = Geocoder.search("#{i[0]}, #{i[1]}").first.coordinates %>
  <% @placesCoordinations.push(result) %>
<% end %>

Error :

NoMethodError in Information#full_map_adresses.

Showing /Users/mateuszstacel/Desktop/Meet-and-Eat/app/views/information/full_map_adresses.html.erb where line #10 raised:

undefined method `coordinates' for nil:NilClass
<% @places.each do |i| %>
  <% result = Geocoder.search("#{i[0]}, #{i[1]}").first.coordinates%> //this line is breaking my app
  <% @placesCoordinations.push(result) %>
<% end %>

But if I use only single location or postcode or street address that work but i need to use both of them to be more precision.

<% @places = [] %>
<% @placesCoordinations = [] %>

<% @information.each do |i| %>
  <%  @places.push([i.address1, i.town, i.postcode, information_path(i)]) %>
<% end %>

<% @places.each do |i| %>
  <% result = Geocoder.search("#{i[2]}").first.coordinates %>
  <% @placesCoordinations.push(result) %>
<% end %>
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

The error message undefined methodcoordinates' for nil:NilClassindicates that theGeocoder.search("#{i[0]}, #{i[1]}")itself is successful, butGeocoder.search("#{i[0]}, #{i[1]}").firstsimply returnsnil`.

It seems like your @information array contains at least one address that cannot be resolved. There might be many reasons: Perhaps there is just a typo in the address or it is a very small village or an address in a country which is not supported by the service you are using.

Tip to debug: Change your code to show what it passes to the method and if there were any results. Something like this might help:

<% @places.each do |i| %>
  Address string: <%= "#{i[0]}, #{i[1]}" %>
  <% result = Geocoder.search("#{i[0]}, #{i[1]}").first %>
  Result: <%= result.present? %>
  <% @placesCoordinations.push(result.coordinates) if result.present? %>
<% end %>

Furthermore: I suggest moving code like this to a model, the controller or a helper. It feels like this doesn't belong in an ERB view.

spickermann
  • 100,941
  • 9
  • 101
  • 131
0

Finally that work !

Inside of the model :

class Information < ApplicationRecord
  geocoded_by :address
  after_validation :geocode

  def address
    [address1, address2, town, postcode].compact.join(", ")
  end
end

then in terminal run command :

rake geocode:all CLASS=Information SLEEP=0.25 BATCH=100