我想你可能会认为在酒店里可能有不止一个房间的最低价格相等。
无论如何,如果你有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返回单个实例,但否则它运行良好,谢谢 –