[票务和帐户有两种模式。帐户中有很多票。我正在尝试为每个帐户获取最后创建的票证。
accounts = Account.where(:deleted => false).pluck(:id)
tickets = Ticket
.left_outer_joins(:admin)
.left_outer_joins(:account)
.where(:account_id => accounts)
.where("ticket_status_id != 6").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包含预期的输出。但是问题是上面的代码花费了很多时间。有什么办法可以在获取查询本身中完成所有这些工作?还是有什么方法可以对其进行优化?
ticket_ids = Ticket.order(created_at: :desc).group_by(&:account_id).values
@tickets = Ticket.where(id: ticket_ids)