2017-04-01 64 views
0

我正在建设一个酒店的应用程序,我想通过它的最便宜的房间的价格排序所有酒店,但我似乎无法实现我的目标。排序有很多协会

Roomtype型号>>

class Roomtype < ActiveRecord::Base 
    mount_uploader :image, RimageUploader 
    belongs_to :hotel 
    has_many :order_items 
    default_scope { order(:price => :desc)} 
end 

酒店型号>>

class Hotel < ActiveRecord::Base 
    has_many :roomtypes, -> { order(:price => :desc) } 
    has_many :hotel_images 
    belongs_to :destination 
    belongs_to :area 
    accepts_nested_attributes_for :hotel_images 

    def price 
    price = self.roomtypes.last.price 
    end 

end 

我需要的酒店一default_scope通过Hotel.find(params[:id]).roomtypes.last.price

回答

0

首先Roomtypes是按价格排列

class Roomtype < ActiveRecord::Base 
    belongs_to :hotel 
    default_scope { order(:price => :desc)} 
end 

所以,酒店last roomtypecheapest

我得到了我想要的东西; sorting the list of Hotels by it's cheapest roomtype通过使用阵列进行排序

​​

这对我来说是最好的解决方案!

0
排序

我认为default_scope订单应该是递增的,因为您希望将价格从小到大排序。

default_scope { order(:price => :asc)} 

然后Hotel.first.room_types应该给你你想要的结果。

+0

我不是在谈论房型排序 –

+0

我想**'酒店被排序的最便宜的房间类型'** –

+0

这就是;每个“酒店”有不同的价格**的**房型,但我想要酒店按**最低房型价格** –

1

查找所有酒店按升序排序的最便宜总房型价格。

class Hotel < ActiveRecord::Base 
    has_many :roomtypes 
    default_scope { joins(:roomtypes).group("roomtypes.hotel_id").order("sum(roomtypes.price) asc") } 
    end 

注: Roomtypes表| hotel_id |价格| 您可以根据您的代码要求更改属性名称。

的帮助下通过Dixit Patel