2016-11-22 53 views
1

我有兩個ActiveRecord型號 - ResidenceApartment根據子女的具體屬性訂購ActiveRecord實例

class Residence < ActiveRecord::Base 
    has_many :apartments 
end 

class Apartment < ActiveRecord::Base 
    belongs_to :residence 
end 

apartments表具有字段price_from(單價)和area。所以總價的公寓是price_from * area

我也定義一個實例方法用於住宅

def min_price_for_apartment 
    apartments.minimum("price_from*area") 
end 

我能夠住宅升序/與調用此範圍降序排序。

#scope: with_children, -> { where(published: true).includes(:apartments).joins(:apartments) } 

scope: sort_by_unit_price_asc, -> { with_children.order('apartments.price_from') } 
# scope: sort_by_unit_price_asc, ->{adding desc to the end of previous scope} 

我應該怎麼做,以最低公寓價格對住宅進行分類?

UPDATE:我已經找到了用純SQL的解決方案,現在需要翻譯爲AR

# select residences.name from residences inner join apartments on residences.id = apartments.residence_id group by (residences.id) order by min(apartments.price_from*apartments.area) 

    name  
----------- 
Lorem 
Ipsum 
Quod 
Maritimus 
Amet 
(5 rows) 

附:我知道其他相關的問題和答案,但他們都沒有幫助我。我也意識到要實施基於前端的解決方案,並將這些值傳遞給data-attributes並根據它們進行排序。

回答

0

這解決了我的問題。只需加入以備將來參考,如果有人需要。

scope :with_children, -> { where(published: true).joins(:apartments).group('residences.id') } 

    scope :sort_by_price_sqm_asc, -> { with_children.order("MIN(apartments.price_from)") } 
1
scope: sort_by_unit_price_asc, lambda {     
    with_children.group('residences.id').order('MIN(apartments.price_from * apartments.area') 
} 
+0

謝謝你的回答,但我已經試過了,並得到這樣的錯誤'PG :: GroupingError:錯誤:列「apartments.id」必須出現在GROUP BY子句中或用於聚合函數中' ps在進行對比後輸出單引號 - )) p.p.s查看我的問題更新。 – marmeladze