2016-04-23 96 views
1

我有以下型號:發現的2種型號的組合最便宜的價格與範圍

class Rim < ActiveRecord::Base 
    has_many :wheels 

    scope :cheapest, -> { minimum(:price) } 
end 

class Tyre < ActiveRecord::Base 
    has_many :wheels 

    scope :cheapest, -> { minimum(:price) } 
end 

class Wheel < ActiveRecord::Base 
    belongs_to :rim 
    belongs_to :tyre 
end 

基本上每一個輪輞和輪胎有價格,而當你把2一起,價格組合的價格,但不是所有的輪輞和輪胎凸輪結合,所以我不能簡單地搜索最便宜的RimTyre並把它們放在一起。我不得不通過表wheels上列出的所有條目。

我如何在Wheel上創建一個範圍以獲得最便宜的車輪?

回答

1

定義,計算它的方法:

class Wheel < ActiveRecord:Base 
    belongs_to :rim 
    belongs_to :tyre 
    def self.cheapest 
    all.min_by{|wheel| wheel.rim.price + wheel.tyre.price} 
    end 
end 

> Wheel.cheapest 
#=> (Cheapest wheel) 

更新:基於範圍的解決方案,工作原理:

scope :cheapest, -> { 
    includes(:rim, :tyre).joins(:rim, :tyre).order("('rims'.price + 'tyres'.price) ASC") 
    }