2013-08-23 111 views
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 

這沒有返回正確的記錄。有任何想法嗎?

回答

2

在汽車模型定義範圍:

class Car 
    has_many :wheels 

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

然後讓所有汽車行駛爆胎:

Car.having_flat_wheels 
+0

感謝您的建議 - 不幸的是,我認爲這將返回一個車每平輪,所以如果一輛車有4個扁平輪胎,它將被添加4次到一個陣列。我只是在尋找一批帶有扁平輪胎的汽車。 –

+0

BTW我更喜歡使用實例方法範圍,所以: 高清having_flat_wheels 其中(「wheels.flat =?」,真).joins(:車輪) 結束 我似乎無法弄清楚如何使用汽車模型的has_flats?方法在where子句中是這樣的: def self.with_flats where(:has_flats?) end –

+0

@psrabbit:所以你想說的是,有多個扁平輪子的汽車出現不止一次,你想要獨特的汽車。 –