Как исправить ошибку "неопределенный метод" в моем Rails Geocoder? - PullRequest
0 голосов
/ 08 февраля 2019

Мой код работает в консоли, но не в приложении

➜  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]

Мой код:

<% @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 %>

Ошибка:

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 %>

Но еслиЯ использую только одно местоположение, почтовый индекс или почтовый адрес, которые работают, но мне нужно использовать их оба для большей точности.

<% @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 %>

Ответы [ 2 ]

0 голосов
/ 08 февраля 2019

Наконец-то это работает!

Внутри модели:

class Information < ApplicationRecord
  geocoded_by :address
  after_validation :geocode

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

, затем в команде запуска терминала:

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

0 голосов
/ 08 февраля 2019

Сообщение об ошибке undefined method координаты 'для nil: NilClass indicates that the Geocoder.search ("# {i [0]}, # {i [1]}") itself is successful, but Geocoder.search ("# {i [0]}, # {i [1]} "). first simply returns nil`.

Похоже, ваш массив @information содержит хотя бы один адрес, который не может быть разрешен.Причин может быть много: Возможно, в адресе есть просто опечатка, или это очень маленькая деревня или адрес в стране, которая не поддерживается службой, которую вы используете.

Совет по отладке: ИзменитьВаш код, чтобы показать, что он передает в метод, и если были какие-либо результаты.Может помочь что-то подобное:

<% @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 %>

Более того: я предлагаю перенести подобный код на модель, контроллер или помощника.Такое ощущение, что это не относится к представлению ERB.

...