我想你可能會認爲在酒店裏可能有不止一個房間的最低價格相等。
無論如何,如果你有100家酒店要考慮,那麼你可能會發現每個酒店運行一個查詢來找到最便宜的房間是不可接受的。
如果是這樣,您可能需要深入SQL來優化搜索(並且還可以通過組合查詢來查找酒店和查詢來順利查找房間)。
像這樣的東西應該是高性能的。
def find_hotels
# hotels near query
number_of_people = params[:adults_number].to_i + params[:children_number].to_i
# rooms with the right capaciy
# rooms with the best price
@rooms = Room.where(hotel: Hotel.near(params[:place], 20)).
where("capacity >= :number_of_people", {number_of_people: number_of_people}).
where("not exists (select null
from rooms r2
where r2.hotel_id = rooms.hotel_id and
r2.capacity >= :number_of_people and
r2.room_price <= rooms.room_price and
r2.id <= rooms.id)", , {number_of_people: number_of_people})
end
它找到的房間,在所需的容量和更便宜的價格在同一家酒店沒有另一個。事實上,假設您只希望每個酒店返回一個單人房間,情況會更進一步。
如果希望所有客房的最低費率返回,使用:
def find_hotels
# hotels near query
number_of_people = params[:adults_number].to_i + params[:children_number].to_i
# rooms with the right capaciy
# rooms with the best price
@rooms = Room.where(hotel: Hotel.near(params[:place], 20)).
where("capacity >= :number_of_people", {number_of_people: number_of_people}).
where("not exists (select null
from rooms r2
where r2.hotel_id = rooms.hotel_id and
r2.capacity >= :number_of_people and
r2.room_price < rooms.room_price)", , {number_of_people: number_of_people})
end
這只是給你所有沒有最便宜的房間最便宜的_room每家酒店... –
@DavidGeismar對不起,看錯你的問題。我更新了我的答案。 –
find_by返回單個實例,但否則它運行良好,謝謝 –