Best performance wise query to get parent of queried nested resource

54 Views Asked by At

I am implementing an availability model nested within a listing. Its for a rental app.

class Listing
  has_many :availabilities,  dependent: :destroy 
end 

class Availability
  belongs_to :listing   
end

availabilities table has start and end date columns.

I am writing a query through search form to find listings where availabilities are present and the date given in the form lies in between start and end dates fo those availabilities.

My query in a class method looks like:

def self.search(params)
  date = params[:date]
  listingsids = Availability.where('startdate <= ?', date).where('enddate >= ?', date).pluck('listing_id')
  products = Listing.where(id: listingsids)
end

However i feel this is not efficient. I wish I can write Listing.joins(:availability) and then use it but rails won't allow it. I can only join the other way which will give me a relation with availability objects and I want listings i.e. parent resource.

How can I make it more efficient and reduce number of queries I am doing?

Will appreciate your help :)

1

There are 1 best solutions below

0
John Hayes-Reed On

You should be able to use joins on listing to get you availablity relations, joins works using the relation name, not the model name, so instead of joins(:availability) you should be using joins(:availabilities). Something like this should work and use just a single query for your case:

Listing.joins(:availablities).where('availability.startdate <= ?', date).where('availability.enddate >= ?', date)

notice that joins uses the relation name joins(:availabilities) but the string in the where uses the table name where('availability.startdate <=?', date)