Skip to content

Instantly share code, notes, and snippets.

@all4miller
Last active November 3, 2023 14:47
Show Gist options
  • Save all4miller/9d3047e69a8e47afc2e3974bb31dea93 to your computer and use it in GitHub Desktop.
Save all4miller/9d3047e69a8e47afc2e3974bb31dea93 to your computer and use it in GitHub Desktop.
# 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