查找具有范围

时间:2016-04-23 11:41:43

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有以下型号:

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个放在一起时,价格是两个价格的组合,但不是所有的轮辋和轮胎凸轮组合,所以我可以&#39;简单搜索最便宜的RimTyre并将它们组合在一起。我必须仔细检查表wheels中列出的所有条目。

如何在Wheel上创建一个范围以获得最便宜的车轮?

1 个答案:

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