Question

I have two models : Product and Location.

class Location
  has_many :products
end

class Product
  belongs_to :location
end

When I use the geocoder gem, I can use a near scope, that allow me to select every location around a specific address. Something like :

@locations_near_paris = Location.near("Paris")

Now, I want to make a collection of products, that are close from Paris, using the @locations_near_paris collection. How can I do that ?

I did the following, but I feel it's not a good practice...

close_locations.each do |l|
  unless l.products.nil?
    l.products.each do |p|
      close_products << p
    end
  end
end
Was it helpful?

Solution

I don't know if the geocoder method returns an AR, but let's assume it does not.

location_ids = Location.near("Paris").collect do |location|
  location.id
end

paris_products = Product.where(location_id: location_ids)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top