Rails postgresql left join using has_may order by created_at

Rails postgresql left join using has_may order by created_at

我有两个模型,分别命名为 'customer' 和 'membership'。客户可以有很多会员资格。我想按最近取消会员资格的日期升序或降序显示客户。我的查询看起来像这样

@customers = Customer
  .joins('LEFT JOIN memberships on memberships.customer_id = customers.id')
  .includes(:partner, :affiliate, active_membership: :plan)
  .group('customers.id')
  .order('memberships.created_at DESC, memberships.cancelled_at DESC')
  .page(params[:page])
  .per(100)
class Customer
  has_many :memberships

  def self.order_by_latest_membership
     left_joins(:memberships) # no need to use a SQL string
       .group(:id) # you only need to group by customers.id
       .order(Membership.arel_table[:created_at].maximum.desc) # MAX(memberships.created_at) DESC
  end
end
Customer.order_by_latest_membership
        .includes(:partner, :affiliate, active_membership: :plan)
        .page(params[:page])