Search code examples
ruby-on-railsassociationshas-onerails-geocoder

Collecting a set of has_one associations in an array


I have a model, Offer. Each Offer has_one Location. I'm trying to use the Geocoder gem method near to get all nearby Locations. The method is used like this:

@nearby_locations = Location.near(address, 100, :order => :distance)

I'm not sure how to replace Location, in Location.near(), with each Offer's associated location. I can access each Offer object's location with @first_offer.location, but the near method is called on the entire Location table. How can I collect all the Offer.locations into an array so that I can use this method on them?

Thanks in advance. I hope I made sense. If not, just leave a comment.


Solution

  • Not sure that I fully understand your question but I'll answer it as best I can. offer.location returns a collection of location objects so you can iterate over these objects and call the near method on each of them:

    offer.location.each do |location|
      location.near
    end
    

    However, I don't think this will work with the near method because it acts as a class level scope. It is not designed to work on an individual record.

    The Geocoder gem does provide other methods that you can use on individual records, for example distance_from. So you could do something like:

    offer.location.each do |location|
      location.distance_from([40.714,-100.234])
    end
    

    Checkout the Geocoder docs for other available method calls.