0

How can I write a rails4 active record equivalent query for the following MySQL query?

SELECT c.id,c.account_name,sum(i.balance) as balance from clients c, invoices i 
where c.id = i.client_id GROUP BY  c.id

1 Answer 1

1

Client.joins(:invoices).select('clients.id, clients.account_name, sum(invoices.balance) as balance').group('clients.id')

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to write query with out join?
Client.joins(:invoices) is equivalent to from clients c, invoices i where c.id = i.client_id.
But you can also use the find_by_sql method: Clients.find_by_sql "SELECT c.id,c.account_name,sum(i.balance) as balance from clients c, invoices i where c.id = i.client_id GROUP BY c.id" should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.