I\'m struggling how to have Ruby on Rails do this query right... in short: to join on a has_many
relation but only via the most recent record in that r
I struggled quite a bit with the exact same issue in an application with a huge amount of rows and after trying various novel solutions like lateral joins and subqueries the best performing and by far simplest solution was just to add a foreign key to the table that points to the latest row and use an association callback (or a db trigger) to set the foreign key.
class AddLatestEmploymentToEmployees < ActiveRecord::Migration[6.0]
def change
add_reference :employees, :latest_employment, foreign_key: { to_table: :employments }
end
end
class Employee < ActiveRecord::Base
has_many :employments, after_add: :set_latest_employment
belongs_to :latest_employment,
class_name: 'Employment',
optional: true
private
def set_latest_employment(employment)
update_column(:latest_employment_id, employment.id)
end
end
Employee.joins(:latest_employment)
.where(employments: { status: :active })
It really shines if the amount of associated records is huge like it was in my case as you can eager load the latest record without the memory issues which occur if you load the entire has_many
association.