Как исправить ошибку "неопределенный метод" в моем Rails Geocoder?
Мой код работает в консоли, но не в приложении
➜ 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 ответа
Наконец то работа!
Внутри модели:
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
Сообщение об ошибке undefined method
координаты для nil: NilClassindicates that the
Geocoder.search ("# {i [0]}, # {i [1]}")itself is successful, but
Geocoder.search ("# {i [0]}, # {i [1]}"). Firstsimply 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.