I have 2 tables. due_loans and payments. Payments table has due_loan_id. Now I want to find all payments belonging to a due loan and perform the calculations in a below SQL. This sql query is working perfectly in MySQL workbench. However, I am unable to make work in Rails. I don't know how to pass variables and group in find_by_sql.
select d.id dueid, d.issue_loan_id, d.duedate,d.dueamount, sum(ifnull(amount, 0))paid, dueamount - sum(ifnull(amount, 0))balance from due_loans d
left join payments p
on d.id = p.due_loan_id
where d.issue_loan_id = 15
group by dueid
If there is no payment for a corresponding due loan then I am assigning a 0 for calculations. Among other solutions, this is what I tried.
def get_due_loans_results
@dueloans = DueLoan.find_by_sql(["select d.id dueid, d.issue_loan_id, d.duedate, d.dueamount, sum(ifnull(amount, 0))paid, dueamount - sum(ifnull(amount, 0))balance from due_loans d
left join payments p
on d.id = p.due_loan_id
where d.issue_loan_id =?", params[:issue_loan_id]].group_by => 'dueid')
respond_to do |format|
format.json {render json: @dueloans}
end
end
