Advanced query in Ruby On Rails (Activerecord)

Asked

Viewed 146 times

0

I need to make a query for a report more or less like this:

Produto.include(:clientes).where('count(produto.id) < cliente.quantidade')

In sql would be more or less like this:

SELECT 
    C.NOME, C.QUANTIDADE, COUNT(P.ID)
FROM PRODUTOS AS P 
LEFT JOIN CLIENTES AS C ON P.CLIENTE_ID = C.ID 
WHERE COUNT(P.ID) < C.QUANTIDADE

How to do this using the Active Record?

2 answers

0

I don’t have much experience with Active Record, but see if it gives you a light:

Produto.find(:all,
            joins:  "INNER JOIN `clientes` ON clientes.id = produtos.cliente_id" ,
            select: "clientes.nome, clientes.quantidade, count(produtos.id)", 
            group:  "clientes.nome, clientes.quantidade")
  • I couldn’t make it work on Rails 4. I think this way only in previous versions. Thank you.

0


It is not possible to do Where with Count this way, you need to use the having. That solved the problem.

Produto.joins(:cliente)
       .group(:nome, :quantidade)
       .having('count(produtos.id) < clientes.quantidade')
       .count(:id)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.