lundi 23 mars 2015

Using geocoder to get the nearest has_many relation for use in a search form

I'm using the geocoder and pg_search gems and have two models set up like this.


Person Model



class Person < ActiveRecord::Base
has_many :locations

pg_search_scope :search_by_text_fields, ...(search scope stuff here)...

end


Location Model



class Location < ActiveRecord::Base
belongs_to :person
geocoded_by :full_address
after_validation :geocode, if: ->(obj){ obj.zipcode.present? and obj.changed? }

end


I can't for the life of me figure out how to combine search_by_text_fields() and near() to find all the People sorted by their nearest location while also having the .distance attribute that near() assigns to any location results when it is called.


The end result I'm looking for is something along the lines of this.


@people = Person.search_by_nearest(:query, :location, :radius)


Which I could then use like this in a view



<ul>
<% @people.each do |person| %>
<li>
<%= link_to "#{person.name} - #{person.nearest_location.distance} Miles", @person %>
</li>

<% end %>
<ul>

Aucun commentaire:

Enregistrer un commentaire