2

次の 2 つのモデルがあるとします。

class Wheel
  belongs_to :car

  def self.flat
    where(flat: true)
  end

class Car
  has_many :wheels

  def flats
    self.wheels.flat
  end

  def has_flats?
    flats.count > 0
  end

タイヤがパンクしているすべての車のクエリが必要です。なぜこれが車のモデルで機能しないのだろうか?:

def self.with_flats
  where(:has_flats?)
end

また

def self.with_flats
  where(:has_flats? == true)
end

これは正しいレコードを返しません。何か案は?

4

1 に答える 1

2

Car モデルでスコープを定義します。

class Car
  has_many :wheels

  scope :having_flat_wheels, joins(:wheels).where("wheels.flat=?", true).uniq
  ......
end  

次に、タイヤがパンクしているすべての車を取得するには、次のようにします。

Car.having_flat_wheels
于 2013-08-23T21:01:28.657 に答える