根据子级的特定属性对ActiveRecord实例进行排序

时间:2016-11-22 11:06:31

标签: ruby-on-rails postgresql activerecord

我有两个ActiveRecord模型 - ResidenceApartment

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}

如何以最低公寓价格对住宅进行分类?

更新:我找到了纯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)

P.S。我知道关于SO的其他相关问题和答案,但他们都没有帮助我。我也知道要实现基于前端的解决方案,将这些值传递给data-attributes并根据它们进行排序。

2 个答案:

答案 0 :(得分:1)

scope: sort_by_unit_price_asc, lambda {                
  with_children.group('residences.id').order('MIN(apartments.price_from * apartments.area')
}

答案 1 :(得分: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)") }