【问题标题】:count with has_many in rails在 rails 中使用 has_many 计数
【发布时间】:2010-02-14 15:30:20
【问题描述】:

我有一个 OrderOrderdetails

Orderdetails belongs_to Order

Order has_many Orderdetails

我正在尝试将以下查询转换为 ActiveRecord count 函数

select Count(*) 
from orderdetails A, orders B 
where A.prodid='6' and A.orderid= B.id and B.custid='11'

我试过了:

@count = Orderdetail.count(:conditions => "prodid = 6 and order.custid = 11")

但是,这会产生错误:

PGError: ERROR:  syntax error at or near "order"
LINE 1: ...unt_all FROM "orderdetails" WHERE (prodid = 6 and order.cust...

编辑 我改为订购s

但现在我收到此错误:

ActiveRecord::StatementInvalid: PGError:错误:缺少 FROM 子句 表“订单”第 1 行的条目: ...unt_all FROM "orderdetails" WHERE (prodid = 6 和 orders.cus...

【问题讨论】:

  • 表名不应该是“orders”吗?
  • 涂料。修复了一些东西。现在我得到不同的错误。如何在 from 中添加订单?

标签: ruby-on-rails activerecord


【解决方案1】:

您需要添加:joins => :order',因为您的条件包含订单表中的元素(这就是您收到错误missing FROM-clause 的原因),请尝试:

@count = Orderdetail.count(:joins => :order, :conditions => "prodid = 6 and orders.custid = 11")

在条件下使用数组更好(更安全):

@count = Orderdetail.count(:joins => :order, :conditions => ["prodid = ? and orders.custid = ?", 6, 11])

【讨论】:

    【解决方案2】:

    我认为您应该彻底阅读一些有关关联如何在 Rails 中工作的文档。 Try this guide.

    您无需在 :conditions 中编写任何 SQL 即可完成您需要的操作。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多