0

I'm issuing 2 queries, one that collects the IDs in the order I need them to be and they're passed into the 2nd query which gets the information, this is my first query:

Location.near([lat, lng], 1, units: :km).order("distance").map(&:id)

Each Location has an associated Venue which I query like so:

Venue.where("location_id IN (?)", location_ids)

I want the venues queried to have the same order their respective locations. For instance if location 1 is the first location has ID 5 and is associated to a venue with ID 10 I want that venue to be the first result in the 2nd query as well.

8vius
  • 5,786
  • 14
  • 74
  • 136

1 Answers1

0

You need to order the venues according after extracting the location_ids:

I assume that you have an association in venue belongs_to :location:

class Venue < ActiveRecord::Base
  belongs_to :location
end

so your code will be:

location_ids = Location.near([lat, lng], 1, units: :km).map(&:id)
Venue.joins(:location).where(locations: {id: location_ids }).order("locations.distance")
mohameddiaa27
  • 3,587
  • 1
  • 16
  • 23