How do I build a query in Ruby on Rails that joins on the max of a has_many relation only and includes a select filter on that relation?

前端 未结 7 1871
走了就别回头了
走了就别回头了 2021-01-06 12:56

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

7条回答
  •  青春惊慌失措
    2021-01-06 13:34

    Since the title includes ARel. The following should work for your example:

    employees = Employee.arel_table
    employments = Employment.arel_table
    max_employments = Arel::Table.new('max_employments')
    e2 = employments.project(
          employments['employee_id'], 
          employments['id'].maximum.as('max_id')
         ).group(employments['employee_id'])
    me_alias = Arel::Nodes::As.new(e2,max_employments)
    
    res = employees.project(Arel.star)
          .join(me_alias).on(max_employments['employee_id'].eq(employees['id'])).
          .join(employments).on(employments['id'].eq(max_employments['max_id']))
    
    
    Employee.joins(*res.join_sources)
      .where(employments: {status: :inactive})
    

    This should result in the following

    SELECT employees.* 
    FROM employees 
    INNER JOIN (
        SELECT 
           employments.employee_id, 
           MAX(employments.id) AS max_id 
        FROM employments 
        GROUP BY employments.employee_id
        ) AS max_employments ON max_employments.employee_id = employees.id 
    INNER JOIN employments ON employments.id = max_employments.max_id
    WHERE 
      employments.status = 'inactive'
    

提交回复
热议问题