Last active
November 3, 2023 14:47
-
-
Save all4miller/9d3047e69a8e47afc2e3974bb31dea93 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# BAD each iteration loads invoice model | |
class Company < ApplicationRecord | |
has_many :invoices | |
end | |
class Invoice < ApplicationRecord | |
belongs_to :company | |
end | |
Company.active.each do |company| | |
SMSService.msg(company.contact_number, company.invoices.last&.total_cost) | |
end | |
# GOOD eager load latest invoices | |
class Company < ApplicationRecord | |
has_many :invoices | |
has_one :latest_invoice, -> { merge(Invoice.latest) }, class_name: :Invoice, inverse_of: :company | |
end | |
class Invoice < ApplicationRecord | |
belongs_to :company | |
scope :latest, -> do | |
from( | |
<<~SQL | |
( | |
select distinct on (company_id) invoices.* | |
from invoices | |
order by company_id, id desc | |
) invoices | |
SQL | |
) | |
end | |
end | |
Company.active.includes(:latest_invoice).each do |company| | |
SMSService.msg(company.contact_number, company.latest_invoice&.total_cost) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment