我有Order
和Orderdetails
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 ......
答案 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来执行您需要的操作。