Count with has_many in rails

I have OrderandOrderdetails

Orderdetails belongs_to Order

Order has_many Orderdetails

I am trying to convert the following query to an ActiveRecord function count

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

I tried:

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

However, this gives an error:

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

Edit I reordered s

but now I get this error:

ActiveRecord :: StatementInvalid: PGError: ERROR: missing FROM-clause entry for tables "orders" LINE 1: ... unt_all FROM "orderdetails" WHERE (prodid = 6 and orders.cus ...

+3
source share
2 answers

You need to add :joins => :order', because your condition contains an element from the order table (why you get the error missing FROM-clause), try:

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

It is also better (safer) to use an array in conditions:

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

, , . .

SQL :conditions, , .

-1

Source: https://habr.com/ru/post/1732757/


All Articles