在rails中使用has_many计数

时间:2010-02-14 15:30:20

标签: ruby-on-rails activerecord

我有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 ......

2 个答案:

答案 0 :(得分:4)

您需要添加: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])

答案 1 :(得分:-1)

我认为你应该彻底阅读一些关于协会如何在rails中工作的文档。 Try this guide

您无需在:conditions中编写任何SQL来执行您需要的操作。