如何写条件on/with加入table?

How to write conditions on/with the joined table?

有Ticket和Account两种模式。帐户有很多票。我正在尝试为每个帐户获取最后创建的票。

accounts = Account.where(:deleted => false).pluck(:id)    
tickets = Ticket.left_outer_joins(:account)
    .where(:account_id => accounts)
    .order(created_at: :desc)

  ticket_ids = Array.new
  accounts.each do |account|
    ticket = tickets.where(:account_id => account).order(created_at: :desc).limit(1).first
    if !ticket.blank?
      ticket_ids.push(ticket.id)
    end
  end

  @tickets = tickets.where(:id => ticket_ids).order(created_at: :desc)

以上代码有效,@tickets 包含预期的输出。但问题是上面的代码花了很多时间。有什么办法可以在获取查询本身中完成所有这些工作吗?或者有什么办法可以优化吗?

我正在使用的数据库:Mysql

ticket_ids = Ticket.order(created_at: :desc).group_by(&:account_id).values
@tickets = Ticket.where(id: ticket_ids)

我会尝试用子查询来解决这个问题。

ticket_ids = Ticket
  .select('MAX(tickets.id)')
  .joins(:account)
  .where(accounts: { deleted: false })
  .group(account_id)

@tickets = Tickets
  .where(id: ticket_ids).order(created_at: :desc)