0

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

MySQL screenshot

1 Answer 1

1

Did you try like:

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 = ? group by dueid", params[:issue_loan_id]])
Sign up to request clarification or add additional context in comments.

1 Comment

Now I have and it works. I thought group is always a last argument. Thanks a lot.

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.