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 relation and then can apply a filter/select on that relation.
Here's a super simple variant that captures my struggle:
Let's say I have a table of Employees
and a table of Employments
. An employee has_many employments
. An employment
has a status
of :active
or :inactive
.
class Employee < ActiveRecord::Base
has_many :employments
end
class Employment < ActiveRecord::Base
belongs_to :employee
end
To keep it simple, let's say there is one employee
: Dan and he has two employments
: an old one (by created_at
) that is :inactive
and a new one that is :active
.
dan = Employee.create(name: 'Dan')
Employment.create(employee: dan, created_at: 2.years.ago, status: :inactive)
Employment.create(employee: dan, created_at: 3.months.ago, status: :active)
So in effect, you could say: "Dan has worked twice and is currently actively employed."
What I want is the Rails query for saying: "find me the employees who are inactive". And that should return an empty set because Dan's latest employment
is :active
. So I can't just do: Employee.joins(:employments).where(employments: { status: :inactive })
because it would match the old employment
and thus return the Dan employee
record.
I need a way to say: "find the employees who are inactive based on the most recent employment record only".
But I don't know how to do that in Rails.
I feel like I'm missing something... that it should be quite simple... but I can't figure it out.
Thanks!