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 1796
走了就别回头了
走了就别回头了 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:36

    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.

    0 讨论(0)
提交回复
热议问题