MySQL - Select the maximum from a column based on an association

45 views Asked by At

I am working with Rails 6.1.7 and attempting to write this with Arel. In this situation, I have 2 models, that have a polymorphic relationship to each other. Model A has_many associated Model B records, with a foreign key on the Model B table. What I need to get is a collection of Model B records, one for each of the Model A foreign keys. The kicker here is that the Model B record needs to have the 'highest' or most recent created_at date. When I group the records, The record that I get for each of the Model A foreign keys has the lowest created_at date, which is not what I need.

An example table of data:

Model A:

id Column B
1 etc
2 etc
3 etc
4 etc

Model B:

id impressionable_type impressionable_id created_at
1 'Model A' 1 1/1/24
2 'Model A' 1 1/2/24
3 'Model A' 1 1/3/24
4 'Model A' 1 1/4/24
5 'Model A' 1 1/5/24

So, for example, when I group the records by impressionable_id, for 'Model A id = 1', the record that is returned for Model B is 'Model B id = 1', with the 'lowest' created_at date. When in reality, I need each returned Model B created_at date to be the most recent.

So far the closest I have gotten is this:

 target_table = ModelB.arel_table
 accession_table = ModelA.arel_table

 subquery = ModelB.project(Arel.star)
                  .where(target_table[:impressionable_type].eq('ModelA'))
                  .where(target_table[:impressionable_id].gteq(start_id))
                  .order(target_table[:created_at].desc)
                  .group(target_table[:impressionable_id])

subquery.to_sql

I guess I just need a way to group records by a polymorphic relationship, and return the record with the 'highest', or most recent created_at date.

0

There are 0 answers