sql - Counting associations where child model's attribute = x -
trying count of driver's cars when manual transmission = true. (driver has_many cars; car belongs_to driver, etc.)
my current code:
<% @driver = driver.find(1) %> <% driver.cars.where("car.manual = true").count %>
returns error:
pg::undefinedtable: error: missing from-clause entry table "car" line 1: ...ars" "cars"."driver_id" = $1 , (car.m... ^ : select count(*) "cars" "cars"."driver_id" = $1 , (car.manual= true)
when remove ".count", seem find relationship, because prints:
#<car::activerecord_associationrelation:0x007fea6ddf4c88>
i tried
<%= @driver.cars.where(manual = true).count %>
but returns count of driver's cars.
i suspect problem "manual = true" syntax, i'm new writing queries i'm missing stunningly obvious. if can me figure out i'm going wrong, i'd appreciate it. (or, of course, if there's better way this.)
the driver
class should declare relationship:
class driver has_many :cars # other things end
and then, have pass hash where
conditions:
<%= @driver.cars.where(manual => true).count %>
or using new ruby hash syntax:
<%= @driver.cars.where(manual: true).count %>
you can debug query being sent database with
<%= @driver.cars.where(manual: true).to_sql %>
Comments
Post a Comment