2016-04-23 13 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") 
    } 
を:作品スコープベースのソリューション
関連する問題