Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Geocoder - Still learning

I'm sure it's a simply issue due to me not fully understanding how bits fit together in Rails...

I've followed the rails cast but I'm having trouble implementing it into my app (I've had it working stand-alone).

The error I get is

undefined method `nearbys'

Here's what I've got: user.rb

  geocoded_by :full_address   
  after_validation :geocode

  def full_address
    [address1, address2, address3, city, country, postcode].compact.join(', ')   
  end

users_controller.rb

def index
    @title = "All users"

    if params[:search].present?
      @users = User.near(params[:search], 50, :order => :distance)
    else
      @users = User.all
    end
end

index.html.erb

<h3>Nearby locations</h3>
<ul>
<% for user in @users.nearbys(10) %>
  <li><%= link_to user.address1, user %> (<%= user.distance.round(2) %> miles)</li>
<% end %>
</ul>

_sidebar.html.erb

            <%= form_tag users_path, :method => :get do %>
                <p>
                <%= text_field_tag :search, params[:search] %>
                <%= submit_tag "Search Near", :name => nil %>
                </p>
            <% end %>

Thanks

If I comment out the .nearbys

<% for user in @users#.nearbys(10) %>
  <li><%= link_to user.latitude, user %> (<%= user.distance.round(2) %> miles)</li>
<% end %>

The search works. Could this be a problem with the install of geocoder?

like image 555
Chris Avatar asked Oct 09 '22 21:10

Chris


1 Answers

The function nearbys is a function on your model, not on a collection of models. The variable @users contains a collection of User models. You need to call the function on a single model instance, for example for each user in @users.

As an example, but not sure if you really want this:

<% @users.each do |user| %>
  <% user.nearbys(10).each do |near_user| %>
    <li><%= link_to near_user.latitude, near_user %> (<%= near_user.distance.round(2) %> miles)</li>
  <% end %>
<% end %>

(Note that I also changed the for user in @users to use @users.each do |user|, which is more "Rubyish".)

like image 148
rdvdijk Avatar answered Oct 12 '22 23:10

rdvdijk