简体   繁体   English

活动记录按最小值排序

[英]Active Record sort by min value

I have a few models, City, Hotel, and Room. 我有一些模型,城市,酒店和房间。 City has_many hotels, hotels has_many rooms. 城市has_many酒店,酒店has_many房间。 Each room has a price. 每个房间都有价格。 I'm trying to sort by the lowest price room, asc and desc. 我正在尝试按价格最低的房间,升序和降序排序。

In my results, I'm also showing the lowest price for a hotel. 在我的结果中,我还显示了酒店的最低价格。 I'm able to successfully sort by price ass with this 我可以用这个成功按价格屁股排序

City.first.includes(hotel: :rooms).order("rooms.price asc")

But since I want to always show the lowest price, this doesn't work if I want to sort high to low since it sorts by the highest room price for a hotel. 但是,由于我想始终显示最低价格,因此如果我要按从高到低的顺序排序,这是行不通的,因为它按酒店的最高房价排序。

Is there a way to sort by a hotels minimum room price? 有没有办法按酒店的最低房价排序? If I try to order by MIN(rooms.price) desc I get an error. 如果我尝试按MIN(rooms.price) desc订购, MIN(rooms.price) desc收到错误消息。

City model 城市模型

attr_accessible :name
has_many :hotels

Hotel model 酒店模型

attr_accessible :city_id, :name
has_many :rooms
belongs_to :city

City model 城市模型

attr_accessible :hotel_id, :name, :price
belongs_to :hotel

Please have a try with 请尝试一下

@rooms = Room.includes([:hotel => [:city]]).select('hotel_id, MIN(price) AS price').group('hotel_id').order('MIN(rooms.price) ASC')

In your view file 在您的视图文件中

<% @rooms.each do |room| %>
 <div>
   <div><%= room.hotel.name</div>
   <div><%= room.hotel.city%></div>
   <div><%= room.price%></div>
 </div>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM