ActiveRecord Equivalent SQL for given statement


ActiveRecord Equivalent SQL for given statement



Association



Budget


Budget


has_many :approvers



Approver


Approver


belongs_to :budget



Requirement



In other worlds (lets say there are 3 budgets)



I have following ruby code, which is causing performance issue, I want to change this to equivalent SQL or ActiveRecord Statement:



Problematic Code


budgets.archived(false).includes(:approvers).select do |b| b.approvers.empty? end.any?



My Solution which is not giving correct result


budgets
.archived(false)
.where("not exists (select 1 from approvers where approvers.budget_id = budgets.id)")
.any?



Any suggestion is appreciated.



NOTE: I am trying to check if any of the budgets (among thousands of budget) if there is a budget which don't have approver assigned to it.




1 Answer
1


all_budgets_with_no_approvers = Budget.joins('left outer join approvers on budget.id = approvers.budget_id').where(approvers: { budget_id: nil })



This will return all budgets with no approvers allocated.





Thanks Rishid, will try this solution out.
– przbadu
Jul 3 at 12:09





This worked right?
– Rashid D R
Jul 3 at 12:28





Yep, working as expected :)
– przbadu
Jul 3 at 13:20






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages