2014-09-19 38 views
0

當手動變速器= true時試圖計算駕駛者的汽車數量。 (驅動程序的has_many汽車;汽車司機belongs_to的,等等)計數兒童模型的屬性= x的關聯

我當前的代碼:

<% @driver = Driver.find(1) %> 
<% driver.cars.where("Car.manual = true").count %> 

返回此錯誤:

PG::UndefinedTable: ERROR: missing FROM-clause entry for table "car" 
LINE 1: ...ars" WHERE "cars"."driver_id" = $1 AND (Car.m... 
                  ^
: SELECT COUNT(*) FROM "cars" WHERE "cars"."driver_id" = $1 AND (Car.manual= true) 

當我刪除了 「.Count之間」,它似乎找關係,因爲它打印:

#<Car::ActiveRecord_AssociationRelation:0x007fea6ddf4c88> 

我也試過

<%= @driver.cars.where(manual = true).count %> 

但是,這返回了所有司機的汽車的計數。

我懷疑問題在於我的「manual = true」語法,但我對編寫查詢相當陌生,所以我可能錯過了一些非常明顯的東西。如果任何人都可以幫我弄清楚我要出錯的地方,我會很感激。 (或者,當然了,如果有更好的方法來做到這一點。)

回答

0

Driver類應申報的關係:

class Driver 
    has_many :cars 
    # other things 
end 

然後,你必須散列傳遞給where條件:

<%= @driver.cars.where(manual => true).count %> 

或使用新的Ruby哈希語法:

<%= @driver.cars.where(manual: true).count %> 

您可以隨時調試正在發送到數據庫的查詢

<%= @driver.cars.where(manual: true).to_sql %>