gpt4 book ai didi

ruby-on-rails - 在 rails 中用 has_many 计数

转载 作者:行者123 更新时间:2023-12-04 08:46:38 25 4
gpt4 key购买 nike

我有一个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: ERROR: missing FROM-clause entry for table "orders" LINE 1: ...unt_all FROM "orderdetails" WHERE (prodid = 6 and orders.cus...

最佳答案

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

关于ruby-on-rails - 在 rails 中用 has_many 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2261569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com