【问题标题】:Counting associations where child model's attribute = x计算子模型的属性 = x 的关联
【发布时间】:2014-09-19 12:26:10
【问题描述】:

在手动变速箱 = true 时尝试计算 Driver 的汽车数量。 (司机有_很多车;车属于司机等)

我当前的代码:

<% @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”语法上,但我对编写查询还很陌生,所以我可能遗漏了一些非常明显的东西。如果有人可以帮助我找出哪里出错了,我将不胜感激。 (或者,当然,如果有更好的方法来做到这一点。)

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 2020-07-24
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      相关资源
      最近更新 更多