I have a table of employees and another table of employments. A given employee can have one or more employments. I want to return a relation of employees but joining with their most recent employment, based on a created_at
date on the employment.
I put a sqlfiddle in place: http://sqlfiddle.com/#!17/b0a3d/2 but that's the basic SQL so it returns a single row for each employee and with the employment data for that employee that corresponds to their latest employment.
NOTE: the sqlfiddle is me thinking about the problem from a SQL perspective, but what I really am after is how to do this via Ruby on Rails. How to join Employee
records with Employment
records but only pulling the latest Employment
record. (hopefully this helps clarify).
So Employee.includes(:employments)
basically does what the sqlfiddle does.
I need something a bit fancier to join the employee and employment data (with latest employment).
I welcome any thoughts.