我有两个ActiveRecord模型 - Residence
和Apartment
。
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
并根据它们进行排序。
答案 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)") }